Как изменить string на int

I have a TextBoxD1.Text and I want to convert it to an int to store it in a database. How can I do this?

Here is the version of doing it via an Extension Method that has an option to set the default value as well, if the converting fails. In fact, this is what I used to convert a string input to any convertible type:

using System;
using System.ComponentModel;

public static class StringExtensions
{
    public static TOutput AsOrDefault<TOutput>(this string input, TOutput defaultValue = default)
        where TOutput : IConvertible
    {
        TOutput output = defaultValue;

        try
        {
            var converter = TypeDescriptor.GetConverter(typeof(TOutput));
            if (converter != null)
            {
                output = (TOutput)converter.ConvertFromString(input);
            }
        }
        catch { }

        return output;
    }
}

For my usage, I limited the output to be one of the convertible types: https://learn.microsoft.com/en-us/dotnet/api/system.iconvertible?view=net-5.0. I don’t need crazy logics to convert a string to a class, for example.

To use it to convert a string to int:

using FluentAssertions;
using Xunit;

[Theory]
[InlineData("0", 0)]
[InlineData("1", 1)]
[InlineData("123", 123)]
[InlineData("-123", -123)]
public void ValidStringWithNoDefaultValue_ReturnsExpectedResult(string input, int expectedResult)
{
    var result = input.AsOrDefault<int>();

    result.Should().Be(expectedResult);
}

[Theory]
[InlineData("0", 999, 0)]
[InlineData("1", 999, 1)]
[InlineData("123", 999, 123)]
[InlineData("-123", -999, -123)]
public void ValidStringWithDefaultValue_ReturnsExpectedResult(string input, int defaultValue, int expectedResult)
{
    var result = input.AsOrDefault(defaultValue);

    result.Should().Be(expectedResult);
}

[Theory]
[InlineData("")]
[InlineData(" ")]
[InlineData("abc")]
public void InvalidStringWithNoDefaultValue_ReturnsIntegerDefault(string input)
{
    var result = input.AsOrDefault<int>();

    result.Should().Be(default(int));
}

[Theory]
[InlineData("", 0)]
[InlineData(" ", 1)]
[InlineData("abc", 234)]
public void InvalidStringWithDefaultValue_ReturnsDefaultValue(string input, int defaultValue)
{
    var result = input.AsOrDefault(defaultValue);

    result.Should().Be(defaultValue);
}

Here is the version of doing it via an Extension Method that has an option to set the default value as well, if the converting fails. In fact, this is what I used to convert a string input to any convertible type:

using System;
using System.ComponentModel;

public static class StringExtensions
{
    public static TOutput AsOrDefault<TOutput>(this string input, TOutput defaultValue = default)
        where TOutput : IConvertible
    {
        TOutput output = defaultValue;

        try
        {
            var converter = TypeDescriptor.GetConverter(typeof(TOutput));
            if (converter != null)
            {
                output = (TOutput)converter.ConvertFromString(input);
            }
        }
        catch { }

        return output;
    }
}

For my usage, I limited the output to be one of the convertible types: https://learn.microsoft.com/en-us/dotnet/api/system.iconvertible?view=net-5.0. I don’t need crazy logics to convert a string to a class, for example.

To use it to convert a string to int:

using FluentAssertions;
using Xunit;

[Theory]
[InlineData("0", 0)]
[InlineData("1", 1)]
[InlineData("123", 123)]
[InlineData("-123", -123)]
public void ValidStringWithNoDefaultValue_ReturnsExpectedResult(string input, int expectedResult)
{
    var result = input.AsOrDefault<int>();

    result.Should().Be(expectedResult);
}

[Theory]
[InlineData("0", 999, 0)]
[InlineData("1", 999, 1)]
[InlineData("123", 999, 123)]
[InlineData("-123", -999, -123)]
public void ValidStringWithDefaultValue_ReturnsExpectedResult(string input, int defaultValue, int expectedResult)
{
    var result = input.AsOrDefault(defaultValue);

    result.Should().Be(expectedResult);
}

[Theory]
[InlineData("")]
[InlineData(" ")]
[InlineData("abc")]
public void InvalidStringWithNoDefaultValue_ReturnsIntegerDefault(string input)
{
    var result = input.AsOrDefault<int>();

    result.Should().Be(default(int));
}

[Theory]
[InlineData("", 0)]
[InlineData(" ", 1)]
[InlineData("abc", 234)]
public void InvalidStringWithDefaultValue_ReturnsDefaultValue(string input, int defaultValue)
{
    var result = input.AsOrDefault(defaultValue);

    result.Should().Be(defaultValue);
}

Currently I’m doing an assignment for college, where I can’t use certain expressions, such as the ones above, and by looking at the ASCII table, I managed to do it. It’s a far more complex code, but it could help others that are restricted like I was.

The first thing to do is to receive the input, in this case, a string of digits; I’ll call it String number, and in this case, I’ll exemplify it using the number 12, therefore String number = "12";

Another limitation was the fact that I couldn’t use repetitive cycles, therefore, a for cycle (which would have been perfect) can’t be used either. This limits us a bit, but then again, that’s the goal. Since I only needed two digits (taking the last two digits), a simple charAtsolved it:

 // Obtaining the integer values of the char 1 and 2 in ASCII
 int semilastdigitASCII = number.charAt(number.length() - 2);
 int lastdigitASCII = number.charAt(number.length() - 1);

Having the codes, we just need to look up at the table, and make the necessary adjustments:

 double semilastdigit = semilastdigitASCII - 48;  // A quick look, and -48 is the key
 double lastdigit = lastdigitASCII - 48;

Now, why double? Well, because of a really «weird» step. Currently we have two doubles, 1 and 2, but we need to turn it into 12, there isn’t any mathematic operation that we can do.

We’re dividing the latter (lastdigit) by 10 in the fashion 2/10 = 0.2 (hence why double) like this:

 lastdigit = lastdigit / 10;

This is merely playing with numbers. We were turning the last digit into a decimal. But now, look at what happens:

 double jointdigits = semilastdigit + lastdigit; // 1.0 + 0.2 = 1.2

Without getting too into the math, we’re simply isolating units the digits of a number. You see, since we only consider 0-9, dividing by a multiple of 10 is like creating a «box» where you store it (think back at when your first grade teacher explained you what a unit and a hundred were). So:

 int finalnumber = (int) (jointdigits*10); // Be sure to use parentheses "()"

And there you go. You turned a String of digits (in this case, two digits), into an integer composed of those two digits, considering the following limitations:

  • No repetitive cycles
  • No «Magic» Expressions such as parseInt

Теги: java, string, типы данных, преобразование строки в число, преобразование числа в строку

В некоторых случаях при программировании на Java нам нужно выполнить преобразование строки в число или числа в строку. Это бывает, если мы имеем величину определённого типа и желаем присвоить эту величину переменной другого типа. Преобразования типов в Java осуществляются разными способами, давайте рассмотрим наиболее популярные из них.

Как преобразовать строку в число в Java?

Речь идёт о преобразовании String to Number. Обратите внимание, что в наших примерах, с которыми будем работать, задействована конструкция try-catch. Это нужно нам для обработки ошибки в том случае, когда строка содержит другие символы, кроме чисел либо число, которое выходит за рамки диапазона предельно допустимых значений указанного типа. К примеру, строку «onlyotus» нельзя перевести в тип int либо в другой числовой тип, т. к. при компиляции мы получим ошибку. Для этого нам и нужна конструкция try-catch.

Преобразуем строку в число Java: String to byte

Выполнить преобразование можно следующими способами:

C помощью конструктора:

    try {
        Byte b1 = new Byte("10");
        System.out.println(b1);
    } catch (NumberFormatException e) {
        System.err.println("Неправильный формат строки!");
    }

С помощью метода valueOf класса Byte:

    String str1 = "141";
    try {
        Byte b2 = Byte.valueOf(str1);
        System.out.println(b2);
    } catch (NumberFormatException e) {
        System.err.println("Неправильный формат строки!");
    }

С помощью метода parseByte класса Byte:

    byte b = 0;
    String str2 = "108";
    try {
        b = Byte.parseByte(str2);
        System.out.println(b);
    } catch (NumberFormatException e) {
        System.err.println("Неправильный формат строки!");
    }

А теперь давайте посмотрим, как выглядит перевод строки в массив байтов и обратно в Java:

    String str3 = "20150";
    byte[] b3 = str3.getBytes();
    System.out.println(b3);

    //массив байтов переводится обратно в строку 
    try {
      String s = new String(b3, "cp1251");
      System.out.println(s);
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }

Преобразуем строку в число в Java: String to int

Здесь, в принципе, всё почти то же самое:

Используем конструктор:

    try { 
        Integer i1 = new Integer("10948");
        System.out.println(i1);
    }catch (NumberFormatException e) {  
        System.err.println("Неправильный формат строки!");  
    }   

Используем метод valueOf класса Integer:

    String str1 = "1261";
    try {
        Integer i2 = Integer.valueOf(str1);
        System.out.println(i2);    
    }catch (NumberFormatException e) {  
        System.err.println("Неправильный формат строки!");  
    }  

Применяем метод parseInt:

    int i3 = 0;
    String str2 = "203955";
    try {
        i3 = Integer.parseInt(str2);
        System.out.println(i3);  
    } catch (NumberFormatException e) {  
        System.err.println("Неправильный формат строки!");  
    }     

Аналогично действуем и для других примитивных числовых типов данных в Java: short, long, float, double, меняя соответствующим образом названия классов и методов.

Как преобразовать число в строку в Java?

Теперь поговорим о преобразовании числа в строку (Number to String). Рассмотрим несколько вариантов:

1. Преобразование int to String в Java:

   int i = 53;
   String str = Integer.toString(i);
   System.out.println(str);   

2. Преобразование double to String в Java:

   double  i = 31.6e10;
   String str = Double.toString(i);
   System.out.println(str);  

3. Преобразуем long to String в Java:

   long  i = 3422222;
   String str = Long.toString(i);
   System.out.println(str);         

4. Преобразуем float to String в Java:

   float  i = 3.98f;
   String str = Float.toString(i);
   System.out.println(str);      

В этой статье мы рассмотрим, как мы можем преобразовать строку (string) в целое число (int) в языке программирования C++.

1. Использование std::stoi

Часто нам может понадобиться преобразовать числовые строки в целые числа. Для этого нам помогут определенные способы, чтобы быстро сделать преобразование.

Рассмотрим ниже два способа преобразования строки в целое число.

Для преобразования объекта std::string в целое число рекомендуется использовать эту опцию в C++. Она принимает строку как входное значение и возвращает целое число.

Вот простой пример:

#include <iostream>
#include <string>
 
using namespace std;
 
int main() {
    string inp = "102";
    cout << "Input String: " << inp << endl;
 
    // Use std::stoi() to convert string to integer
    int res = stoi(inp);
 
    cout << "Integer: " << res << endl;
    return 0;
}

На выходе:

Input String: 102
Integer: 102

Это сработает и для строк с отрицательными значениями.

Однако это вызовет исключение std::invalid_argument, если строка имеет неправильный формат.

Поэтому мы должны использовать в нашем коде обработку исключений, если строка не валидируется.

#include <iostream>
#include <string>
 
using namespace std;
 
int main() {
    string inp = "Hello";
 
    cout << "Input String: " << inp << endl;
 
    // Use std::stoi() to convert string to integer
    try {
        // Wrap up code in try-catch block if string is not validated
        int res = stoi(inp);
        cout << "Integer: " << res << endl;
    }
    catch(std::invalid_argument e) {
        cout << "Caught Invalid Argument Exceptionn";
    }
    return 0;
}

На выходе:

Input String: Hello
Caught Invalid Argument Exception

Надеюсь, это даст вам хорошее представление о том, как вы можете преобразовать строку в целое число в C++.

Рассмотрим ниже еще один способ, используя функцию atoi() в стиле C.

2. Использование atoi()

Мы можем преобразовать строку C ( char* ) в целое число, используя atoi(char* str).

Мы можем применить эту логику к нашему объекту std::string, сначала преобразовав его в строку C.

#include <iostream>
#include <string>
 
using namespace std;
 
int main() {
    string inp = "120";
 
    cout << "Input String: " << inp << endl;
 
    // Convert std::string to C-string
    const char* c_inp = inp.c_str();
 
    // Use atoi() to convert C-string to integer
    int res = atoi(c_inp);
 
    cout << "Integer: " << res << endl;
    return 0;
}

На выходе:

Input String: 120
Integer: 120

Как видите, это дает нам тот же результат, что и раньше!

27 июля 2020 в 13:46
| Обновлено 7 ноября 2020 в 01:19 (редакция)
Опубликовано:
| Оригинал
Статьи, C++

Часто задаваемый вопрос по типам String/int в Java: Как преобразовать тип String в тип Int?

Решение: используя метод parseInt класса Java Integer. Метод parseInt переводит тип String в Int, и вызывает исключение NumberFormatException, если строка не может быть приведена к целочисленному значению.

Посмотрим на два коротких примера.

  • Простой пример преобразования “ string to integer” в Java
  • Изучаем преобразование строки в число Java — полный пример перевода String в int
  • Преобразование строки в число Java — пояснение
  • Преобразование строки в число Java- дополнительные замечания
  • Преобразование строки в число Java — резюме

Игнорируя исключение, которое может возникнуть, всё, что нужно сделать для перевода String в int, умещается в одну строку кода:

int i = Integer.parseInt(myString);

Если строка, представленная переменной myString, является корректным целым числом, например, “1”, “200”, и т.п., она будет приведена к типу int. Если преобразование окончится неудачей, будет вызвано исключение NumberFormatException. Поэтому ваш код должен быть немного длиннее, чтобы учитывать это, как показано в следующем примере.

Ниже приведен полный код примера программы. Она демонстрирует процесс перевода в Java строки в целое число и обработку возможного исключения NumberFormatException:

public class JavaStringToIntExample{  public static void main (String[] args)  {    // String s = "fred";  // Используйте эту строку для теста исключения    String s = "100";     try    {      // перевод String в int выполняется здесь      int i = Integer.parseInt(s.trim());       // выводим значение после преобразования      System.out.println("int i = " + i);    }    catch (NumberFormatException nfe)    {      System.out.println("NumberFormatException: " + nfe.getMessage());    }  }}

В приведенном выше примере метод Integer.parseInt(s.trim()) используется для перевода строки s в целое число i в следующей строке кода:

int i = Integer.parseInt(s.trim());

Если попытка преобразования оканчивается неудачей (например, если вы пытаетесь привести строку fred к целому типу), то метод parseInt класса Integer вызовет исключение NumberFormatException, которое необходимо обработать в блоке try/catch.

В этом примере на самом деле не нужно использовать метод trim() класса String. Но в реальных программах он понадобится, поэтому я применил его здесь.

Раз уж мы обсуждаем эту тему, вот несколько замечаний о классах String и Integer:

  • Метод Integer.toString(int i) используется для преобразования из типа int в класс Java String.
  • Для преобразования объекта String в объект Integer используйте метод valueOf() класса Integer вместо parseInt().
  • Если нужно приводить строки к другим примитивным типам Java, например, long, используйте методы Long.parseLong(), и т.п.

Надеюсь, что этот пример перевода String в int в Java был полезным. Если у вас есть вопросы или замечания, оставляйте их в комментариях.

Converting numbers to strings or vice-versa is a bit confusing in itself. We may have to perform such conversions while working with numbers and strings together. Despite being simple operations, many coders either fail or get confused while doing this.  

Before knowing how we should convert string to numbers what is the need for conversion : 

You’ll get an error if you try to input a value that isn’t acceptable with the data type. Both C/C++ is a strongly typed languages. You’ll get an error if you try to input a value that isn’t acceptable with the data type. Not just in inputs but you will get an error while performing operations. There is a fair chance of getting both syntax and logical errors.

For example, assume we had a numeric string “673” that we want to convert to a numeric type. We’ll need to utilize a function that converts a string to an integer and returns 673 as the numeric value.

Furthermore, converting a text to an integer is more difficult than converting doubles to integers using type casting. We are not allowed to perform type casting because int and string both are not in the same Object hierarchy.

For example, you cannot do this since it will give error

C++

#include <string>

using namespace std;

int main() {

   string str = "7";

   int num;

   num = (int) str;

}

The error after compiling will be:

hellp.cpp:9:10: error: no matching conversion for C-style cast from ‘std::__1::string’ (aka
    ‘basic_string<char, char_traits<char>, allocator<char> >’) to ‘int’
 num = (int) str;
       ^~~~~~~~~
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/string:875:5: note: candidate function
  operator __self_view() const _NOEXCEPT { return __self_view(data(), size()); }
  ^
1 error generated.

For Number to String Conversion refer to the article – Converting Numbers to String in C++

Converting Strings to Numbers

There are 3 major methods to convert a number to a string, which are as follows:

  • Using string Stream 
  • Using stoi()
  • Using atoi()
     

1. Using stringstream class or sscanf()

stringstream(): This is an easy way to convert strings of digits into ints, floats, or doubles. A number stream declares a stream object which first inserts a string, as a number into an object, and then uses ‘stringstream()’ to follow the internal conversion.

To use it, first, add the line #include <sstream> to the start of your program to include the sstream library.

The stringstream is then added and a stringstream object is created, which will retain the value of the string you want to convert to an int and will be utilized during the conversion process.

To extract the string from the string variable,  use <<  operator.

Next, you input the newly converted int value to the int variable using the >> operator.

Example:

CPP

#include <iostream>

#include <sstream>

using namespace std;

int main()

{

    string s = "12345";

    stringstream geek(s);

    int x = 0;

    geek >> x;

    cout << "Value of x : " << x;

    return 0;

}

// A stringstream is similar to input/output
// file stream. We need to declare a stringstream
// just like an fstream, for example: 
stringstream ss;

// and, like an fstream or cout, 
// we can write to it:
ss << myString; or 
ss << myCstring; or
ss << myInt;, or float, or double, etc.

// and we can read from it:
ss >> myChar; or
ss >> myCstring; or
ss >> myInt;  

To summarize, stringstream is a convenient way to manipulate strings. ‘sscanf() is a C style function similar to scanf(). It reads input from a string rather than standard input. 

GeeksforGeeks-CPP-Foundation-Course

Syntax of sscanf:

int sscanf ( const char * s, const char * format, ...);

Return type: Integer

Parameters:

  • s – string used to retrieve data
  • format – a string that contains the type specifier(s)…
  • : – arguments contain pointers to allocate storage with the appropriate type.

There should be at least as many of these arguments as the number of values stored by the format specifiers.

On success, the function returns the number of variables filled. In the case of an input failure, before any data could be successfully read, EOF is returned.

C++

#include <iostream>

using namespace std;

int main()

{

    const char* str = "12345";

    int x;

    sscanf(str, "%d", &x);

    cout << "nThe value of x : " << x << endl;

    return 0;

}

C

#include <stdio.h>

int main()

{

    const char* str = "12345";

    int x;

    sscanf(str, "%d", &x);

    printf("nThe value of x : %d", x);

    return 0;

}

Output

The value of x : 12345

Similarly, we can read float and double using %f and %lf respectively.

C

#include <stdio.h>

int main()

{

    const char* str = "12345.54";

    float x;

    sscanf(str, "%f", &x);

    printf("nThe value of x : %f", x);

    return 0;

}

Output

The value of x : 12345.540039

Output 1:

The value of x : 12345.540039 // output of floating number

Output 2:

The value of x : 12345.540000 // output of double number

If the values are the same then why the outputs are different?

The reason behind this is that Floating numbers are all about speed, precision, and convenience in addition to which they use a binary representation to display their output which somewhat brings the output to the closest approximation; that’s why there are those extra digits at the end of the output. In addition to that in double numbers, the value will be shown as it is because double is all about accuracy and reliability, though it consumes more space than float and is also a bit slower than floating numbers. 

2. String Conversion Using stoi()

stoi(): The stoi() function takes a string as an argument and returns its value in integer form. This approach is popular in current versions of C++, and it was first introduced in C++11.And if you observe stoi() a little closer you will find out that it stands for:

   s    to     i()

|  |   |___> integer
|  |_______> to
|__________> String 

Example:

CPP

#include <iostream>

#include <string>

using namespace std;

int main()

{

    string str1 = "45";

    string str2 = "3.14159";

    string str3 = "31337 geek";

    int myint1 = stoi(str1);

    int myint2 = stoi(str2);

    int myint3 = stoi(str3);

    cout << "stoi("" << str1 << "") is " << myint1

         << 'n';

    cout << "stoi("" << str2 << "") is " << myint2

         << 'n';

    cout << "stoi("" << str3 << "") is " << myint3

         << 'n';

    return 0;

}

Output

stoi("45") is 45
stoi("3.14159") is 3
stoi("31337 geek") is 31337

Output:

stoi("45") is 45
stoi("3.14159") is 3
stoi("31337 geek") is 31337 

3. String Conversion Using atoi()

The atoi() function takes a character array or string literal as an argument and returns its value in an integer form. And if you observe atoi() a little closer you will find out that it stands for:

a   to   i
|   |    |____> integer 
|   |_________> to
|_____________> Argument    

Example:

C++14

#include <cstdlib>

#include <iostream>

using namespace std;

int main()

{

    const char* str1 = "42";

    const char* str2 = "3.14159";

    const char* str3 = "31337 geek";

    int num1 = atoi(str1);

    int num2 = atoi(str2);

    int num3 = atoi(str3);

    cout << "atoi("" << str1 << "") is " << num1 << 'n';

    cout << "atoi("" << str2 << "") is " << num2 << 'n';

    cout << "atoi("" << str3 << "") is " << num3 << 'n';

    return 0;

}

C

#include <stdio.h>

#include <stdlib.h>

int main()

{

    char* str1 = "42";

    char* str2 = "3.14159";

    char* str3 = "31337 geek";

    int myint1 = atoi(str1);

    int myint2 = atoi(str2);

    int myint3 = atoi(str3);

    printf("atoi(%s) is %d n", str1, myint1);

    printf("atoi(%s) is %d n", str2, myint2);

    printf("atoi(%s) is %d n", str3, myint3);

    return 0;

}

Output

atoi("42") is 42
atoi("3.14159") is 3
atoi("31337 geek") is 31337

stoi() vs atoi()

1. atoi() is a legacy C-style function. stoi() is added in C++ 11. 

2. atoi() works only for C-style strings (character array and string literal), stoi() works for both C++ strings and C style strings

3. atoi() takes only one parameter and returns integer value.

int atoi (const char * str); 

4. stoi() can take up to three parameters, the second parameter is for starting index and the third parameter is for the base of the input number.

int stoi (const string&  str, size_t* index = 0, int base = 10); 

Exercise: Write your own atof() that takes a string (which represents a floating-point value) as an argument and returns its value as double.

C++

#include <cstdlib>

#include <iostream>

using namespace std;

int main()

{

    const char* str1 = "42.245";

    double num1 = atof(str1);

    cout << "atof("" << str1 << "") is " << num1 << 'n';

    return 0;

}

Output

atof("42.245") is 42.245

4. Using For Loop to convert Strings into number

C++

for ( int i = number.length() -1 ; i >= 0 ; i-- ) {

    int power = number.length() - i -1;

    newNumber += (std::pow( 10.0,  power) * (number[i] - '0'));

}

This article is contributed by Siffi Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article on write.geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.

Java String to Int – How to Convert a String to an Integer

String objects are represented as a string of characters.

If you have worked in Java Swing, it has components such as JTextField and JTextArea which we use to get our input from the GUI. It takes our input as a string.

If we want to make a simple calculator using Swing, we need to figure out how to convert a string to an integer. This leads us to the question – how can we convert a string to an integer?

In Java, we can use Integer.valueOf() and Integer.parseInt() to convert a string to an integer.

1. Use Integer.parseInt() to Convert a String to an Integer

This method returns the string as a primitive type int. If the string does not contain a valid integer then it will throw a NumberFormatException.

So, every time we convert a string to an int, we need to take care of this exception by placing the code inside the try-catch block.

Let’s consider an example of converting a string to an int using Integer.parseInt():

        String str = "25";
        try{
            int number = Integer.parseInt(str);
            System.out.println(number); // output = 25
        }
        catch (NumberFormatException ex){
            ex.printStackTrace();
        }

Let’s try to break this code by inputting an invalid integer:

     	String str = "25T";
        try{
            int number = Integer.parseInt(str);
            System.out.println(number);
        }
        catch (NumberFormatException ex){
            ex.printStackTrace();
        }

As you can see in the above code, we have tried to convert 25T to an integer. This is not a valid input. Therefore, it must throw a NumberFormatException.

Here’s the output of the above code:

java.lang.NumberFormatException: For input string: "25T"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Integer.parseInt(Integer.java:580)
	at java.lang.Integer.parseInt(Integer.java:615)
	at OOP.StringTest.main(StringTest.java:51)

Next, we will consider how to convert a string to an integer using the Integer.valueOf() method.

This method returns the string as an integer object. If you look at the Java documentation, Integer.valueOf() returns an integer object which is equivalent to a new Integer(Integer.parseInt(s)).

We will place our code inside the try-catch block when using this method. Let us consider an example using the Integer.valueOf() method:

        String str = "25";
        try{
            Integer number = Integer.valueOf(str);
            System.out.println(number); // output = 25
        }
        catch (NumberFormatException ex){
            ex.printStackTrace();
        }

Now, let’s try to break the above code by inputting an invalid integer number:

        String str = "25TA";
        try{
            Integer number = Integer.valueOf(str);
            System.out.println(number); 
        }
        catch (NumberFormatException ex){
            ex.printStackTrace();
        }

Similar to the previous example, the above code will throw an exception.

Here’s the output of the above code:

java.lang.NumberFormatException: For input string: "25TA"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Integer.parseInt(Integer.java:580)
	at java.lang.Integer.valueOf(Integer.java:766)
	at OOP.StringTest.main(StringTest.java:42)

We can also create a method to check if the passed-in string is numeric or not before using the above mentioned methods.

I have created a simple method for checking whether the passed-in string is numeric or not.

public class StringTest {
    public static void main(String[] args) {
        String str = "25";
        String str1 = "25.06";
        System.out.println(isNumeric(str));
        System.out.println(isNumeric(str1));
    }

    private static boolean isNumeric(String str){
        return str != null && str.matches("[0-9.]+");
    }
}

The output is:

true
true

The isNumeric() method takes a string as an argument. First it checks if it is null or not. After that we use the matches() method to check if it contains digits 0 to 9 and a period character.

This is a simple way to check numeric values. You can write or search Google for more advanced regular expressions to capture numerics depending on your use case.

It is a best practice to check if the passed-in string is numeric or not before trying to convert it to integer.

Thank you for reading.

Post image by 🇸🇮 Janko Ferlič on Unsplash

You can connect with me on Medium.

Happy Coding!



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Понравилась статья? Поделить с друзьями:
  • Как изменить str на int python
  • Как изменить syswow64
  • Как изменить steam id для обхода бана
  • Как изменить steam emu
  • Как изменить ssl сертификат