The crude way to loop until a valid number is entered, is to ask for a string, attempt to convert it to a number, and keep doing so until this conversion doesn't fail:
import java.util.Scanner;
/**
<P>{@code java StringToNumberWithTesting}</P>
**/
public class StringToNumberWithTesting {
public static final void main(String[] ignored) {
int num = -1;
do {
nfx2 = null;
System.out.print("Number please: ");
String strInput = (new Scanner(System.in)).next();
try {
num = Integer.parseInt(strInput);
} catch(NumberFormatException nfx) {
nfx2 = nfx;
System.out.println(strInput + " is not a number. Try again.");
}
} while(nfx2 != null);
System.out.println("Number: " + num);
}
}
Output:
[C:\java_code\]java StringToNumberWithErrLoop
Number please: etuh
etuh is not a number. Try again.
Number please: 2
Number: 2
But using the absence of an exception as a substitute for logic is never a good idea in a real-world application. A better way is to confirm the string contains a number, for which you can use Commons' NumberUtils.isNumber(s)
import java.util.Scanner;
import org.apache.commons.lang.math.NumberUtils;
/**
<P>{@code java StringToNumberWithTesting}</P>
**/
public class StringToNumberWithTesting {
public static final void main(String[] ignored) {
int num = -1;
boolean isNum = false;
do {
System.out.print("Number please: ");
String strInput = (new Scanner(System.in)).next();
if(!NumberUtils.isNumber(strInput)) {
System.out.println(strInput + " is not a number. Try again.");
} else {
//Safe to convert
num = Integer.parseInt(strInput);
isNum = true;
}
} while(!isNum);
System.out.println("Number: " + num);
}
}
Output:
[C:\java_code\]java StringToNumberWithTesting
Number please: uthoeut
uthoeut is not a number. Try again.
Number please: 3
Number: 3
Some more information: How to check if a String is numeric in Java