I am trying to validate that the user only enters an integer. Is there another way to do this that will make the validation more simplified?
Scanner in = new Scanner(System.in);
System.out.print("Enter the amount of subjects that you need to get an average of: ");
int amount_of_subjects;
while (!in.hasNextInt())
{
// warning statement
System.out.println("Please Enter integer!");
in.nextLine();
}
amount_of_subjects = Integer.parseInt(in.nextLine());
CodePudding user response:
Depending what you want to do with your program.
If you want to only take a valid Integer as input you can use the nextInt() function
Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();
If you want to check if the user is putting in a valid Integer to respond to that you can do something like:
public boolean isNumber(String string) {
try {
Integer.parseInt(string);
return true;
} catch (NumberFormatException e) {
return false;
}
}
CodePudding user response:
It seems your solution is already quite simple. Here is a more minimalist version:
System.out.print("Please enter an integer: ");
while(!scan.hasNextInt()) scan.next();
int demoInt = scan.nextInt();
from https://stackoverflow.com/a/23839837/2746170
Though you would only be reducing lines of code while possibly also reducing readability.
