While loop issue in Java - java

This is a little bit of my code.
System.out.print("Would you like to continue (Y/N)?");
while (!Anwser.equals("Y")){
Anwser = UserInput.next();
System.out.println("Would you like to continue (Y/N)?");
}
This is the answer.
> Would you like to continue (Y/N)?
> Would you like to continue (Y/N)?
Why does it print it out again although I typed Y and the conditions were not met? After this it continues with the code:

A while loop is done zero or more times.
A do while loop is done one or more times.
For a continuation question you do not really care what the user inputs as long as it is a 'Y' or 'y'.
Anything else will terminate the program.
Also with a continuation question the program usually wants to run once. So wrap your code in a do while loop.
do {
// Your code goes here
System.out.print("Would you like to continue (Y/N)?");
Anwser = UserInput.next();
} while (answer.equalsIgnoreCase( "Y"));
As to why your code does not work. Perhaps you should have assigned a value to Answer before the loop starts.

Try changing the value of "Anwser" variable and replace it with the user's input
like this:
System.out.print("Would you like to continue (Y/N)?");
Anwser = UserInput.next();
while (!Anwser.equals("Y")){
System.out.println("Would you like to continue (Y/N)?");
Anwser = UserInput.next();
}

The reason why it is printing twice is because the first line is printing the question outside of the loop, then tests the answer (which was not captured and then relies on what the reference variable was initialized to) then enters the while loop which first gets the input from the user to the last question then prints the question again.
System.out.print("Would you like to continue (Y/N)?"); //prints to screen
//no input captured before test
while (!Anwser.equals("Y")){ //tests the reference variable
Anwser = UserInput.next(); //captures user input after test
System.out.println("Would you like to continue (Y/N)?"); //asks question again
}
The while loop is a a pre-test loop, meaning that it tests the condition before running the code inside. With this code, you're testing the response to the first question to answer the second. So, all you would really need to do if you wanted to keep the while loop is put the question once inside the loop and like so:
while (!Anwser.equalsIgnoreCase("Y"))
{
System.out.println("Would you like to continue (Y/N)?");
Anwser = UserInput.next();
}
Also, since you're just capturing a character, maybe instead of making a String object to hold a character literal, try a char variable. Here is that solution:
char answer = ' ';
Scanner userInput = new Scanner(System.in);
while (answer != 'N') // check for N to end
{
System.out.println("Would you like to continue (Y/N)?");
answer = Character.toUpperCase(userInput.nextLine().charAt(0));
}

Related

Creating while-loop with nested loops in it

I am trying to create a program that picks a random number, and as the user inputs guesses, the program dictates if it's "too high", "too low", AND keeps a running total. But my while loop only extends over the first nested loop I create, and won't cover anything after that.
I'm coding in Blujay on my mac, but received that same issue on a windows desktop, making me believe its a coding error, not a program one
System.out.println("Would you like to play this game? y/n");
Scanner scan = new Scanner(System.in);
playGame = scan.next().charAt(0);
while (playGame == 'y')
System.out.println("Please enter a number in 1-100 range");
userNumber= scan.nextInt();
while in Java, the while loop in the code below only cover(or goes purple / gets highlighted) the line with "while (playgame == y)", and the following print statement, but i need the whole program to be under a while loop so the game can repeat as long as the user says "y".
To make this valid Java code, you first need semicolons at the end of every statement. That's not the fix for your while loop, and maybe in you actual code you already have that, but I'm just pointing it out.
To make a while loop - or any kind of code block - cover multiple statements in Java, you use curly braces {}. Again, maybe your actual code has this, but the way you're wording your question makes me think you probably don't. So that's:
while (condition) {
statement1;
statement2;
...
}
Java does not care about indentation at all, you need the braces and semicolons to make this work.
Wrap the whole code in a while(true) statement and exit it when the user chooses to exit the game:
char playGame;
while (true) {
System.out.println("Would you like to play this game? y/n");
Scanner scan = new Scanner(System.in);
playGame = scan.next().charAt(0);
if (playGame != 'y') break;
System.out.println("Please enter a number in 1-100 range");
int userNumber = scan.nextInt();
System.out.println("You entered: " + userNumber); // or something else
}

This do/while loop repeat for no reason, how to fix it?

I am trying to do a false credit card generator. So basically the problem is that when the user says "No" the program continues and shows "Goodbye" but then it starts all over again and can't find why.
I thought of putting all this do/while loop in a for loop so i can put a break at the end but it led to a dead code (which is logical).
public void generateCode() {
char userAnswer;
Scanner sc = new Scanner(System.in);
do {
System.out.println("Put a bin.");
String binGiven = sc.nextLine();
verificationBin();
showCardNumber();
do {
System.out.println("Do u wanna try again ? (Yes/No)");
userAnswer = sc.nextLine().charAt(0);
} while (userAnswer != 'Y' && userAnswer != 'N');
} while (userAnswer == 'Y');
System.out.println("Goodbye");
sc.close();
}
I expected it to stop when the user says No but it starts all over again
According to image you added you are calling the looping code twice. Once from your constructor and once from your main.
This is your code currently:
Generator gen = new Generator();
gen.generateCode();
However, your constructor inside the generator class contains a call to the same method generateCode() shown here:
this.generateCode();
When you use new Generator() this runs the code inside of the constructor as well, so you are running the same code twice. You can confirm this by attempting to run through the program two times and it should stop executing after the second time.
Remove this.generateCode() as this is not really code that should be ran from a constructor.

Using Scanner object for spell checking as a newbie

Scanner kb = new Scanner(System.in);
String plt;
String msr;
double wgh;
System.out.println("'Welcome to interplanetary weight calculator.");
Thread.sleep(2500);
System.out.println("");
System.out.println("Please choose one planet for calculation:");
System.out.println("1.Venus 2.Mars 3.Jupiter");
System.out.println("4.Saturn 5.Uranus 6.Neptune");
System.out.print(">");
do {
while (!kb.hasNextLine()) {
System.out.println("That's not a planet!");
kb.nextLine(); // this is important!
}
plt = kb.nextLine();
} while (plt.equalsIgnoreCase("Venus"));
System.out.println("Thank you!Now will do calculation on " + plt); }}
I want to make a weight calculator between planets and I also want a spell checker too but when I write something, it just prints out "Thank you! Now, will do the calculation on ....".
It prints out integers too. I can't find where did I do wrong.
Essentially, what happens is that your loop will run once, you can enter something and it will then exit the loop because anything except "venus" (in any combination of upper and lower case) will exit the loop. This is why it will also print numbers, etc.
The solution to this might be to add an ! to the beginning of the condition. This will invert the condition, meaning now only entering "venus" will cause the loop to exit which will result in the program continuing to run everything below the loop. However, there's still not going to be any kind of error message. Spell-checking and error handling would be achieved differently.

Why does this While loop cycle twice?

I made this while loop that is supposed to fulfill functions for different shapes and after it fulfills the function for that shape, it will keep asking for shapes until the user types "Exit". I have only done Triangles so far so I just have some filler functions to fulfill to make sure that it loops correctly. The problem is, after I'm done with triangles, it will print the menu twice before asking for an input instead of just printing once. Can anyone explain this to me?
while(password){
System.out.println();
System.out.println("---Welcome to the Shape Machine---");
System.out.println("Available Options:");
System.out.println("Circles");
System.out.println("Rectangles");
System.out.println("Triangles");
System.out.println("Exit");
String option = keyboard.nextLine();
if(option.equals("Exit")){
System.out.println("Terminating the program. Have a nice day!");
return;
} else if(option.equals("Triangles")){
System.out.println("Triangles selected. Please enter the 3 sides:");
int sideA = 0;
int sideB = 0;
int sideC = 0;
do{
sideA = keyboard.nextInt();
sideB = keyboard.nextInt();
sideC = keyboard.nextInt();
if(sideA<0 || sideB<0 || sideC<0)
System.out.println("#ERROR Negative input. Please input the 3 sides again.");
} while(sideA<0 || sideB<0 || sideC<0);
if((sideA+sideB)<=sideC || (sideB+sideC)<=sideA || (sideA+sideC)<=sideB){
System.out.println("#ERROR Triangle is not valid. Returning to menu.");
continue;
} else {
System.out.println("good job!");
}
}
}
It might be that you are using keyboard.nextLine();. In your code outside the while loop make sure that you are always using .nextLine() and nothing else.
Reasoning: If you use .next(), it'll only consume one word so the next time you call .nextLine(), it'll consume the end of that line.
After you say sideC = keyboard.nextInt() the carriage return that you typed (after typing the number) is still in the input buffer. Then you print the menu and execute String option = keyboard.nextLine(); That command reads up to and including the first newline it finds, which is the newline that is still in the buffer.
So option is now a bare newline character, which does not match "Exit" or "Triangle", so it loops again and prints th menu again.
This problem is caused by left-over characters like space, carriage-return, newline, form-feed in the input buffer.
Since the next keyboard.nextLine() doesn't match any of given options (and since there is no "else" at the bottom of while loop to deal with this case), the control goes into next iteration, prints the options again. Based on surrounding context of processing of input, there are several good answers to address this problem on SO.
Since your intention is to skip over all blanks, carriage-returns, newlines, form-feeds till you get a valid string (option) again, the following code works best in a case like yours.
System.out.println();
System.out.println("---Welcome to the Shape Machine---");
//...
System.out.println("Exit");
String option = keyboard.nextLine();
keyboard.skip("[\\s]*");

An infinite loop while using Scanner - java

I want to ask the user whether he wants to create a file named file.elt or not. I'm trying to do this with a switch statement using Scanner class.
Here is my code:
System.out.println("Do you want to create the file.elt? (Y/N)");
strOption=sc.nextLine();
OUTER:
while (sc.hasNext()) {
switch (strOption) {
case "Y":
case "y":
elements.createElements(file);
break OUTER;
case "N":
case "n":
System.out.println("There will be no file.elt created! .");
break OUTER;
default:
System.out.println("Please, type Y or N.");
strOption=sc.nextLine();
break;
}
}
sc.close();
The sc object is declared at the beginning of the program, where I ask for the name of the file.
The sc declaration is:
String file;
Scanner sc = new Scanner(System.in);
System.out.println("Type the name of the file .dat .");
file=sc.nextLine();
The problem is that the while loop is infinite and I don't know why.
You are not updating strOption.
You should move your strOption=sc.nextLine(); inside your while loop
Also, as TheLostMind pointed out, replace hasNext with hasNextLine.
Edit
You might consider to switch to Console. Also, you may create confirm utility method since it's fairly common task:
private Console console;
...
console = System.console();
...
if (confirm("Do you want to create the file.elt? (Y/N)")) {
elements.createElements(file);
} else {
System.out.println("There will be no file.elt created! .");
}
...
private boolean confirm(String message) {
String answer = console.readLine(message);
while (!answer.matches("[YyNn]")) {
answer = console.readLine("Please, type Y or N.");
}
return "Y".equalsIgnoreCase(answer);
}
Note: This doesn't work in eclipse.
Scanner is state based, and a bit difficult. I would not use it for non-token things.
//strOption=sc.nextLine();
OUTER:
while (sc.hasNextLine()) {
strOption=sc.nextLine();
...
default:
System.out.println("Please, type Y or N.");
//strOption=sc.nextLine();
2 options:
Because sc.hasNext() is always true . you need to call sc.nextLine to advances this scanner past the current line
sc.hasNext() is blocking (as describe in the documents )
if you cn tell if it's realy an infinite loop or blocking call - you will know how to solve it (simply add trace at the beginning of the loop , run the program , and check the output console )
First, don't use labels such as OUTER unless you know what you are doing. In this case it is not needed.
sc.hasNext() returns true (otherwise you wouldn't even enter the loop) and in the loop you don't do anything to change that state (you don't 'consume' the inputstream).
Before you even enter the loop, you read the first line, after which there is apparently more input to be read but you never read that input so sc.hasNext() keeps returning true and the while loop never finishes.
Your break OUTER; breaks to the loop defined in OUTER:, which means it breaks TO the while loop, not OUT of the while loop. Typically people use this construct to break out of an inner loop to an outer loop but as I said before, you're better of not using this construct.
EDIT: I confused labeled breaks with labeled continues. Basically, the break here works as intended but the label is superfluous (and I still advise against using labels).
The problem then is that the first line of input you read probably didn't equals a "y", "Y", "n" or "N" for some reason and since you don't consume the input, sc.hasNext() and strOption still contains the same string which doesn't equal any of your case statements, meaning the loop will go on infinitely.
Either use a plain break; or fix your loop so it consumes the input.
For example:
System.out.println("Do you want to create the file.elt? (Y/N)");
while (sc.hasNext())
{
String inputString = strOption=sc.nextLine();
// handle inputString
}
sc.close();

Categories