Java: how to read an input int
12,703
Solution 1
Use a BufferedReader. Check NumberFormatException. Otherwise very similar to what you have. Like so ...
import java.io.*;
public class ReadInt{
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
boolean check;
int i = 0;
System.out.print("Integer: ");
do{
check = true;
try{
i = Integer.parseInt(in.readLine());
} catch (NumberFormatException e){
System.err.println("Input error - Invalid value for an int.");
System.out.print("Reinsert: ");
check = false;
}
} while (!check);
System.out.print(i + " + 7 = " + (i+7));
}
}
Solution 2
To use with tokens:
int i = Integer.parseInt(in.next());
Then you could do:
int i;
while (true) {
System.out.print("Enter a number: ");
try {
i = Integer.parseInt(in.next());
break;
} catch (NumberFormatException e) {
System.out.println("Not a valid number");
}
}
//do stuff with i
That above code works with tokens.
Related videos on Youtube
Author by
Marco
Updated on June 04, 2022Comments
-
Marco about 2 years
So, I was looking for an efficient way, using Java's standard packages, to read an input integer... For example, I came across the class "Scanner", but I found two main difficulties:
- if I don't insert an int, I'm not actually able to solve the exception;
- this class works with tokens, but my aim is to load the string in its full length.
This is an example of execution I would like to realize:
Integer: eight Input error - Invalid value for an int. Reinsert: 8 secondtoken Input error - Invalid value for an int. Reinsert: 8 8 + 7 = 15
And this is the (incorrect) code I tried to implement:
import java.util.Scanner; import java.util.InputMismatchException; class ReadInt{ public static void main(String[] args){ Scanner in = new Scanner(System.in); boolean check; int i = 0; System.out.print("Integer: "); do{ check = true; try{ i = in.nextInt(); } catch (InputMismatchException e){ System.err.println("Input error - Invalid value for an int."); System.out.print("Reinsert: "); check = false; } } while (!check); System.out.print(i + " + 7 = " + (i+7)); } }
-
Jimmy Thompson over 11 yearsCan you please elaborate on what you mean by
if I don't insert an int, I'm not actually able to solve the exception
?
-
Marco over 11 yearsIt works fine but I don't want to consider tokens.... For example, if I set as input "hello 8 testtest" I don't want to have i = 8, but instead an error, because the whole input is a string in this case