I simply would like to break out of a while true
loop if the user enters in "STOP" into the scanner. Currently my scanner only takes in integers and I believe this is where the problem lies. If I try to type in "STOP" I get many errors saying "exception in thread main". Here is a snippet of my code:
public class algorithm {
private Scanner input = new Scanner(System.in);
int n;
while (true){
System.out.println("Eneter a number to check if it is odd or even, then hit enter: ");
System.out.println("Type 'STOP' to end the program");
n = input.nextInt();
String strN = String.valueOf(n); //convert integer to string
if (new String(strN).equals("STOP")){ //if string is STOP, breaks
System.out.println("Thanks for using my program");
break;
}
if (n % 2 == 0){
System.out.println(n+" is even");
continue;
}
else{
System.out.println(n+" is odd");
continue;
I know I am missing some closing curly braces but rest assured they are all there in my actual code. Thanks.
Here is the error I am getting:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at OddOrEven.algorithm.checker(algorithm.java:13)
at OddOrEven.main.main(main.java:7)