So I am trying to set up a while loop that takes a string at certain lengths and produces outputs based on those lengths and terminates the program when a blank line is entered. This probably isn't the best way to do it but I did a while loop for when the input string isn't 1 character (or just a space). But when I run the code and input something greater than 1 it does nothing until I enter an input again then relays the necessary outputs. I think it has something to do with the block of code below where I attempted to update the string and its length inside the while loop.
String str = keyboard.nextLine();
int strLength = str.length();
while (strLength != 1)
{
str = keyboard.nextLine();
strLength = str.length();
//stuff ...
}
System.out.print("goodbye");
CodePudding user response:
this is because you take first output outside the loop where you declare the string when you came in the loop you directly asked next input so it work on next input. But when you input only space that time it not go in the loop.
CodePudding user response:
You said:
I am trying to set up a while loop that takes a string at certain lengths and produces outputs based on those lengths and terminates the program when a blank line is entered.
Cheers!
Scanner keyboard = new Scanner(System.in);
String str;
do {
System.out.print("Enter something: ");
str = keyboard.nextLine();
if (!str.isBlank()) {
// stuff
System.out.println("Do your stuff");
}
} while (!str.isBlank());
System.out.print("Goodbye !!!");