Convert String to whole in Java

Asked

Viewed 92,747 times

15

How do I capture a String of the user through the Scanner and turn into whole?

4 answers

16

Do something like this:

Scanner s = new Scanner(System.in);
String str = s.nextLine(); /* Vai pegar tudo até a primeira quebra de linha.
                              Garanta que o número é válido!
                           */
try {
       int i = Integer.parseInt(str); // Caso você queira tipo int, que é o usual.
       long l = Long.parseLong(str); /* É essencialmente a mesma coisa que o int, mas tem um
                                          limite de dados maior que o int, por consumir mais
                                          memória para a variável, e, por consequência um limite
                                          superior maior para o valor da variável.
                                       */
} catch (NumberFormatException e) {
  System.out.println("Numero com formato errado!");
} finally {
  s.close(); //fechar o Scanner para gerenciar melhor a memória.
}

The other two numerical types, float and double may be obtained from a string in the same way, but remembering that these functions separate the decimal places with '.' and not with ','!

  • Just be careful not to take one NumberFormatException right?

  • Fact. I’ll improve the answer so hehe

10

Beyond the function Integer.ParseInt, quoted by Mutley, you can also use Integer.ValueOf:

public static int strToInt(String valor, int padrao) 
{
   try {
       return Integer.valueOf(valor); // Para retornar um Integer, use Integer.parseInt
   } 
   catch (NumberFormatException e) {  // Se houver erro na conversão, retorna o valor padrão
       return padrao;
   }
}

To use, do so:

public static void main (String[] args) throws java.lang.Exception
{
    int valor1 = strToInt("2015", 2015);
    int valor2 = strToInt("20iiii5", 2015);

    System.out.println(valor1); // 2015
    System.out.println(valor2); // 2015
}

See DEMO

Note

As mentioned by Gustavo Cinque, Integer.valueOf returns a primitive type, int, whereas Integer.parseInt returns a Integer, choose between one or the other will depend on the purpose of the code.

See more information on this question:

  • 2

    There is a slight difference @Qmechanic, the .valueOf(str) returns a int as long as the Integer.parseInt(str) returns a Integer. Fountain

  • Those who voted against: Can you comment on what’s wrong with the code or what I can do to improve it? The Co-operative Spirit sends hugs!!! : -S

  • What a fright my friend, I thought I was the one who voted against, hehe.

6

Documentation

The first important thing for someone who is starting to study or work with Java is to consult the required class documentation.

For example, Scanner has the method nextInt, which would be the most abbreviated way to solve the problem of reading an integer. There in the documentation, says the exception InputMismatchException will be launched if the input is not a valid integer, so the programmer can treat the exception as best suits you.

Already Integer contains the static methods parseInt and valueOf, which return the numerical value of a String as a primitive (int) or wrapper (Integer), respectively. The use of each depends on the purpose of the code.

Using nextInt

With the nextInt, you can directly read entire input already as numbers. Multiple numbers can be read on the same line, provided they are separated by spaces, for example.

However due to the nature of the command line, the numbers will only be effectively read when the user presses Enter.

Example

final Scanner scanner = new Scanner(System.in);
final int primeiroNumeroDigitado = scanner.nextInt();
System.out.format("Primeiro número digitado: %d%n", primeiroNumeroDigitado);
final int segundoNumeroDigitado = scanner.nextInt();
System.out.format("Segundo número digitado: %d%n", segundoNumeroDigitado);
scanner.nextLine();

Analyzing line by line:

  1. Creates a Scanner pointing to the program input, which usually defaults to what the user types in the command line.
  2. Reads the first integer. At this point, usually the program will pause and wait for the user to type something and press Enter. Upon receiving the first line typed, the nextInt will consume the numerical values until you find something other than a number, then return to normal execution.
  3. Print the number typed.
  4. Reads the second number. If there are characters not consumed, the program tries to read the numbers still in the buffer input. If you find the routine returns immediately, otherwise the program pauses again until it receives another entry, like the first time.
  5. Print the second number typed.
  6. The method nextLine consumes the rest of the line, cleaning the buffer incoming. This can be important if your program makes other entries later in order to eliminate "dirt" that has been typed by mistake on that line.

This program can receive entries such as:

10 20

Or else:

10

20

And both will print the two values correctly.

Using parseInt intelligently

Something boring when you’re testing on the command line is typing something wrong in the middle of a program that reads multiple console data and then having to start all over again.

In order to minimize this problem, you can implement a method that tries to turn the typed line into a number and, if it fails, repeat the operation until it succeeds.

Example

public static int readInt(final Scanner scanner) {
    for (;;) {
        final String linhaDigitada = scanner.nextLine();
        try {
            final int numeroInteiro = Integer.parseInt(linhaDigitada);
            return numeroInteiro;
        } catch (NumberFormatException e) {
            System.out.println("Número inteiro inválido! Tente novamente.");
        }
    }
}

In the code above, we have to:

  • The for generates an infinite loop, broken only when a valid integer is typed in a line of the Scanner. Of course the program can be interrupted as a whole, but it does not continue normally without meeting such condition.
  • The method nextLine returns the next line typed by the user.
  • The method parseInt tries to convert the whole line to an integer. Note, here it is not possible to enter two numbers in a row.
    • If the number is converted to an integer successfully, the method returns the value in the next line and terminates the execution.
    • Otherwise an exception is NumberFormatException will be launched and the block catch will be executed. There, the message that the invalid number is printed on the console to warn the user, such a block terminates and the loop runs again waiting for a valid number

Finally, such a method can be called as follows:

final int terceiroNumeroDigitado = readInt(scanner);
System.out.format("Terceiro número digitado: %d%n", terceiroNumeroDigitado);

This passage reuses the Scanner of the first example. The first line calls the method and the second print the number typed.

An example of interaction:

r

Invalid integer number! Try again.

3

Third number entered: 3

Complete code of the example

public class ScannerInputExample {

    public static int readInt(final Scanner scanner) {
        for (;;) {
            final String linhaDigitada = scanner.nextLine();
            try {
                final int numeroInteiro = Integer.parseInt(linhaDigitada);
                return numeroInteiro;
            } catch (NumberFormatException e) {
                System.out.println("Número inteiro inválido! Tente novamente.");
            }
        }
    }

    public static void main(String[] args) {
        final Scanner scanner = new Scanner(System.in);
        final int primeiroNumeroDigitado = scanner.nextInt();
        System.out.format("Primeiro número digitado: %d%n", primeiroNumeroDigitado);
        final int segundoNumeroDigitado = scanner.nextInt();
        System.out.format("Segundo número digitado: %d%n", segundoNumeroDigitado);
        scanner.nextLine();

        final int terceiroNumeroDigitado = readInt(scanner);
        System.out.format("Terceiro número digitado: %d%n", terceiroNumeroDigitado);
    }

}

Notes

  • Although I explicitly requested the reading of a String with further transformation, I do not believe it to be a rigid requirement. It was probably a way to express yourself, so use nextInt reaches the same goal, but making such "transformation" implicitly.

  • The use of final in variables and parameters may seem exaggerated, but it reinforces the good practice of not reusing variables and, especially for beginners, avoids erroneous attributions as in if (a = b).

  • For more complex inputs, use the Scanner from a text file is more interesting. You spend 5 more minutes preparing some files, use the FileInputStream and that’s it. Think of the time you’ll save by testing the various scenarios of a program you’re developing.

  • I decided to add this answer to an old question, given the high number of views and the answers with few explanations or bad practices.

  • 1

    +1 for the answer, if I could I would have given an extra +1 for not playing in the new duplicate (it sounds like a joke, but some people do it kkkk).

  • 1

    Great answer! + 1

4

Only use the Integer.parseInt().

Example:

String str = "123";
int valor;

valor = Integer.parseInt(str);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.