Check pre conditions for scanner system.in
Code:
public String userInput() {
Scanner in = new Scanner(System.in);
boolean cond = true;
String result;
// do while loop ensures the characters entered are in the correct format
do {
// set cond to false, if input fails any checks then it will be reset to true
cond = false;
// accessing user input
System.out.println("\nType in the characters: ");
String str = in.next();
if (some check fails)
System.out.println("Try Again");
cond = true;
}
result = str
in.reset();
} while (cond);
in.close();
return result;
}
My problem is a null pointer exception because of the in.next() statement, I am unsure how to run a check on input and then if failed, attempt to access the keyboard again without using the same scanner. I have put the scanner initiation/closing within the do while but that changed nothing. The scanner reset wasn't what I was looking for either. I am open to a more appropriate design style if anyone has a recommendation, or just a fix for this one.
Thank You for your help.
Re: Check pre conditions for scanner system.in
Don't close the scanner as it's also closing the underlying streams, i.e. System.in.
Code:
Scanner in = new Scanner(System.in);
boolean cond = true;
String result;
// do while loop ensures the characters entered are in the correct format
do {
// set cond to false, if input fails any checks then it will be reset to true
cond = false;
// accessing user input
System.out.println("\nType in the characters: ");
String str = in.nextLine();
if (some check fails)
System.out.println("Try Again");
cond = true;
}
result = str
} while (cond);
return result;
Re: Check pre conditions for scanner system.in
PROBLEM SOLVED! Thanks All!
-Austin