Okay I can't seem to find a definitive answer to my problem.
I need a program in java that can return a value that the user enters, that is a positive integer.
To differentiate this to many other similar questions, I need to program to not crash upon entering a string. The program will need to repeated prompt the user for a input until a positive integer is inputted. The script would be something like this:
Input: 7.2
Error, try again: -5
Error, try again: -2.4
Error, try again: 3.77777
Error, try again: -1
Error, try again: 0
Error, try again: -33
Error, try again: microwave
Error, try again: -1
Error, try again: 4.2
Error, try again: hello
Error, try again: 3.14159
Error, try again: 4
4 is a positive integer.
It is important that the program does not crash when something like a word is entered. I can't figure out a way for the program to do something like this. I could use hasNextInt
with the scanner, but then I don't know how to check if its greater than zero as the input could be a string in another case.
Could someone help me out with a program that would return the above script? Hugely appreciated.
EDIT: Okay I finally found the answer I was looking for in a different question. This solution does not use parseInt()
, nor does it use try
/catch
, which was what I was looking for. Nice and simple. So here is the solution code:
Scanner in = new Scanner(System.in);
int num;
System.out.print("Input: ");
do {
while (!in.hasNextInt()) {
System.out.print("Error, not integer. Try again: ");
in.next();
}
num = in.nextInt();
if (num<=0){
System.out.print("Error, not positive. Try again: ");
}
} while (num <= 0);
System.out.println(num + " is a positive integer.");