This code is working for the first scanner to accept ints but the second scanner throws a mismatch error. I cannot seem to find why it is doing this. Can anyone help me out? I have tried everything and it is not working. I can get the first scanner to accept strings multiple times. The second scanner will accept ints but if i try to input a string even one time then the program crashes. How can this be resolved?
For more details of full program click here:
pastebin.com/iMgNncMH
Password: ENdu4mWLNm
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(true) {
System.out.println("Enter two integers:");
while (!scanner.hasNextInt()) {
scanner.next();
}
int n1 = scanner.nextInt();
int n2 = scanner.nextInt();
System.out.println();
CodePudding user response:
I looked through the code, and it is working fine on BlueJ Here is the console image. Could you explain a little more about what error you are getting while compilation? Also here's the full code
import java.util.*;
public class prime {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(true) {
System.out.println("Enter two integers:");
while (!scanner.hasNextInt()) {
scanner.next();
}
int n1 = scanner.nextInt();
int n2 = scanner.nextInt();
System.out.println();
}
}
}
CodePudding user response:
The error being thrown is InputMismatchException. Its happening on the n2 why this is happening... idk I'm about as surprised as you are. Weird how it doesn't throw on n1 its the same issue. Perhaps it has something to do with the next int your looking for. Here's what I would suggest. Basic error handling using a Boolean while loop. If the catch is thrown it will never hit that true so two integers must be entered.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n1 = 0;
int n2 = 0;
System.out.println("Enter two integers:");
boolean validEntry = false;
while(!validEntry) {
try {
n1 = scanner.nextInt();
n2 = scanner.nextInt();
validEntry = true;
}
catch(InputMismatchException ex){
System.out.println("Please refrain from entering words. only numbers aloud");
scanner.nextLine();
}
}
}
Ps that other while loop you had is never hit. I can see what you were going for though.