Reputation: 37
say, I want the user to input an integer only but not something like "bacon", is there a way to restrict user input to integers(or other data types) so I don't get any errors and or inputs other than an integer?
Upvotes: 1
Views: 6005
Reputation: 1687
Here is a fully functional example:
import java.util.Scanner;
public class Temp {
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
int num = 0;
String input = "";
String exit = "exit";
boolean isStringNumber = true;//If the String is not Number
System.out.println("NOTE: To exit, type the word exit and press enter key");
while(true){
System.out.println("\nPlease enter a number only...");
input = inp.nextLine();
if(input.equalsIgnoreCase(exit)){break;}
isStringNumber = input.matches("[0-9]+");//Check if no digits in string
if(isStringNumber == false){
System.out.println("\nYou entered a non number " + input);
System.out.println("Remove all non numbers from your input and try again !");
continue;
}else{
num = Integer.parseInt(input);
System.out.println("You entered " + num);
}
}
System.out.println("Exiting program...");
}
}
Upvotes: 1
Reputation: 46
Assuming your Scanner has the name myScanner:
public static int checkMyInput () {
try {
return myScanner.nextInt();
} catch (InputMismatchException e ) {
myScanner.next();
System.out.println("bacon luff");
return 0 ;
}
}
and then you can call that method.
Upvotes: 3