I am creating a program that takes a lot of user input. I have managed to deal with every input error except for the user just pressing enter (the user can press enter (input nothing) repeatedly until they actually input something). I want the user to be prompted to enter again if they enter nothing or just press the enter key.
Example code:
public class TestInput {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean run = true;
while (run) {
System.out.print("Enter 'Hello': ") // How can I get this to appear again if the user just presses enter? (or inputs nothing)
String Hello = in.nextLine()
if (Hello.equals("Hello")) {
run = false;
} else {
// re-loop and ask "Enter 'Hello': " again
}
}
}
}
I would like to know the best way to deal with whitespace input or just no input at all instead of the program allowing the user to press Enter repeatedly. Thanks in advance.
CodePudding user response:
It looks like you want the user to only type in the word 'hello' as well.
Anyway you can achieve what you want with the following check.
if(Hello != null && Hello.trim().length > 0 && Hello.equals("Hello"))
run = false
else
continue;
The first part checks whether Hello has no value (null) the second part checks whether Hello contains anything at all after removing whitespaces with trim()
. The third part checks whether Hello equals "Hello"
CodePudding user response:
You can use a boolean to clean up your code a little. I tried this, works well :)
public class TestInput {
public static void main(String[] args) {
TestInput testInput = new TestInput();
testInput.game(true);
}
private void game(boolean run){
Scanner in = new Scanner(System.in);
while (run) {
System.out.print("Enter 'Hello': "); // How can I get this to appear again if the user just presses enter? (or inputs nothing)
String inputString = in.nextLine();
if (inputString != null && inputString.trim().length() > 0 && inputString.equals("Hello")) {
run = false;
} else {
System.out.println("Please type Hello");
}
}
}
}
CodePudding user response:
First, remove all whitespaces from the string
and then check whether it matches or not
String Hello = str.replaceAll("\\s", "");
if(Hello != null && Hello.size() > 0 && Hello.equals("Hello"))
run = false
else
continue;