Why does my java Scanner.nextLine() code sometimes skip a line? [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I'm trying to understand why my java code doesn't behave as I expect it to do.
I want to print the question once, wait for the user to input their answer, then decide whether to loop back or proceed depending on the answer.
When I run the code below, the question gets printed twice, and the loop didn't stop and wait for user input after its first run.
Scanner input = new Scanner(System.in);
String answer = "";
while (!answer.equals("Yes") && !answer.equals("No")){
System.out.println("abc1");
System.out.println("Do you want to quit the game? Answers: y/n");
System.out.println("abc2");
System.out.println("abc3");
answer = input.nextLine();
System.out.println("abc4");
}
I don't think I need a second .nextLine(), because the first one already consume the end of the input line (\n). But for the sake of experimenting, I modified the code by adding an extra .nextLine() (as shown below). Two problems with this new code:
On the first run (first loop), the code skips the first .nextLine() and waits for user input at the second .nextLine() (I can tell this is the case because "abc3" gets printed before I, as a user, can input anything).
Starting from the second loop, the code prints "abc2", wait for user input, prints "abc3", then wait for user input again.
Scanner input = new Scanner(System.in);
String answer = "";
while (!answer.equals("Yes") && !answer.equals("No")){
System.out.println("abc1");
System.out.println("Do you want to quit the game? Answers: y/n");
System.out.println("abc2");
answer = input.nextLine();
System.out.println("abc3");
answer = input.nextLine();
System.out.println("abc4");
}
I modified the code further (answer = input.nextLine(); vs just answer = input.nextLine();) and still get the same behaviors.
Scanner input = new Scanner(System.in);
String answer = "";
while (!answer.equals("Yes") && !answer.equals("No")){
System.out.println("abc1");
System.out.println("Do you want to quit the game? Answers: y/n");
System.out.println("abc2");
input.nextLine();
System.out.println("abc3");
answer = input.nextLine();
System.out.println("abc4");
}
What do I get wrong here?
Any advice is greatly appreciated!

I found where the mistake was! I left a .nextInt() elsewhere in my code but forgot I needed to consume the end of the line (\n). My (first) .nextLine() finished what had been left off by the .nextInt() without me realizing this was happening.

Related

How to get user code with letter and number on one line? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed yesterday.
Improve this question
I am trying to create a program in which the user enters the card number. The card consists of the first letter 'A' and a four-digit number. Unfortunately, the 'scanner' accepts these values in separate lines, and I would like the user to enter this in one.
System.out.print("Please write the number: ");
// number card A1111
String char1 = sc.nextLine();
int number3 = sc.nextInt();
It seems to me that in this case you need to use String char1 = sc.next(String.valueOf(sc.nextInt())); but the compiler prints me an error.

Java Beginner Guidance [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 months ago.
Improve this question
How do you write a Java program that accepts number as input and based on the value entered, displays a message?
Like
"1" displays "Yes"
"2" displays "No"
The main thing you will want to look into is the Java Scanner. You can import it via import java.util.Scanner; To make a new Scanner which reads from the console you will write:
Scanner userInput = new Scanner(System.in);
Scanners are very versatile, so they are built to read from any input stream. This could be a file, a String, or many other things. Just like System.out is an output stream to the console, System.in is an input stream from the console.
For more information you can read the scanner documentation here.
Now with your scanner created to get a number input we can use the nextInt() method.
int input = userInput.nextInt();
Here is a simple program similar to what you described.
import java.util.Scanner;
public class ScannerInputTest{
public static void main(String[] args){
Scanner userInput = new Scanner(System.in);
System.out.print("Enter Input > ");
int input = userInput.nextInt();
if(input == 1){
System.out.println("Yes");
}else if(input == 2){
System.out.println("No");
}else{
System.out.println("I don't Know");
}
}
}
Since you are just starting out please try your best to read through documentation, and don't just copy and paste answers from here. Try to tinker and change things to get a better understanding.
If you are going to be making a lot of console programs, I highly recommend also looking into switch statements, as if else statements will eventually become very bloated the more branches you need.

Why isn't the text showing up? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I am making a text based game, and my code works fine until this line when i type in "why" it doesn't print "test".
System.out.println( "Fallout: Master's dialogue");
System.out.println(" ");
System.out.println( " So, what shall it be? Do you join the Unity or do you die here? Join! Die! Join! Die! ");
System.out.print( "> ");
Go = keyboard.nextLine();
if (Go.equalsIgnoreCase("join"))
{
System.out.println("Excellent. Your talents will be useful. But first you must tell me everything about your vault.");}
System.out.print("> ");
Look = keyboard.nextLine();
if (Go.equalsIgnoreCase("why"))
{System.out.println("TEST");}
System.out.print("> ");
Look = keyboard.nextLine();
}
I assume Go and Look are string variables.
At the start of the code, you read the user input and stored it in Go:
Go = keyboard.nextLine();
And then you checked whether Go is join:
if (Go.equalsIgnoreCase("join"))
This is all fine and good.
Then, you read user input a second time, and stored it in Look:
Look = keyboard.nextLine();
But you incorrectly checked Go instead:
if (Go.equalsIgnoreCase("why"))
Go has not been changed. Go is still "join", so the condition is never true.
You should check Look instead:
if (Look.equalsIgnoreCase("why"))

how to stop While-Do Loop? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
the System.out.print("\n\n\t\t Do you want to see the next record ? [y/n]"); keeps repeating and repeating how can i stop it when the Records becomes 0.
case 3: //Previous
if (recno!=0) {
String pre;
System.out.print("\n\n\t\t\t\t Previous Record");
System.out.print("\n\n\t\t\t Employee Number: EMP-"+EmpNo[recno]);
System.out.print("\n\t\t\t Employee Name: "+EmpName[recno]);
System.out.print("\n\t\t\t Salary: "+Salary[recno]);
System.out.print("\n\t_________________________________________________________________");
do {
System.out.print("\n\n\t\t Do you want to see the next record ? [y/n]");
pre = reader.readLine();
if(pre.equals("y")) {
recno--;
System.out.print("\n\n\t\t\t Employee Number: EMP-"+EmpNo[recno]);
System.out.print("\n\t\t\t Employee Name: "+EmpName[recno]);
System.out.print("\n\t\t\t Salary: "+Salary[recno]);
}
menu = display.charAt(0);
System.out.print("\n\t_________________________________________________________________");
} while(menu=='n');
System.out.println("Thank You for Using this Program!");
}
else {
System.out.print("\n\n\t\t\t\tRecord Not Found!");
}
break;
To stop the loop use if (condition) break; with the proper condition; put this code in the proper place inside the loop.
You use the key-word "break".
In any loop, whether it is a while, do-while, or for-loop, you can always break the loop with the keyword as a statement "break".
So like this:
do {
if(condition) {
break;
}
while(condition);
In your code, the do-while loop condition is determined by the first character of display being "n". In your loop, display is never updated, so the condition that "n" is the first letter of display is never met. You can also choose to change your logic as the other answers have suggested by using the break statement.
I think you may be looking for a break statement.
This question shows the break in action. The accepted answer shows how to break out of two loops.

Star pyramid with while loop [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am currently puzzled on making a star pyramid.
My product needs to be able to create a pyramid with a user-inputted # of rows. So if I say 3, the pyramid would look like:
*
***
*****
When I enter 3, my pyramid (based on my code below) looks like:
*
***
*****
I'm having trouble making the spaces get deducted when going down a row. I seem to have other parts down accurately, so my question is, how do I deduct spaces for each following row by 1 after the initial amount of spaces? Could I get help on how to fix my code? (while using a while loop). Feel free to comment on any other parts of my code if it seems inaccurate though.
At the moment this is what my code looks like:
import java.util.Scanner;
public class AstPyramid{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("How tall do you want your pyramid to be? Rows: ");
int rowCounter = keyboard.nextInt();
int baseLength = 1;
int starsInRow = 1;
while (baseLength <= rowCounter){
int starCounter = 1;
int whiteSpace = rowCounter/2;
while (whiteSpace >= 0){
System.out.print(" ");
whiteSpace--;
}
while (starCounter <= starsInRow){
System.out.print("*");
starCounter++;
}
System.out.println();
baseLength++;
starsInRow=starsInRow+2;
}
}
}
Update: I updated this question many times and already have received an answer pertaining to it. Could this question be un-held now? I'm not sure if editing this post notifies anybody, but it is worth another try.
In your code, the first inner-loop that you are using to print the white space, always runs for rowCounter / 2 times. That is the problem. It should ideally start at that value, and keep decreasing for each iteration of the outer loop.
You could have a spacesPerRow variable and assign it an initial value of rowCounter / 2, outside the outer loop. Then on each outer-loop iteration, you can decrease it. And use this spacesPerRow in your first inner loop to print the spaces.
Your spacesPerRow should be decremented once for each iteration of the outer loop. An ideal place would be right after your first inner loop finishes.
To moderators & question down-voters:
I can't add comments, so I'll add my thoughts here. The first few lines of the question precisely mention the problem: "I want to do X, but my code is doing Y". And the OP is not able to figure out why.
I also believe the code doesn't include a lot of unnecessary parts either.
I am wondering why this is considered off-topic, put on hold, and has two down-votes.

Categories