Need to hit enter twice, addition nextLine() not solving the problem - java

I have been researching this problem for a while now and I thought I found a solution, but to no avail.
I am creating a text based game, and when I ask the user to enter their choice as a number 1-4, they have to hit enter twice. I have to hit enter twice whether or not my nextInt() is followed by nextLine() (which is what most of my research has uncovered.)
public void askPlayer() {
int playerLocation = player.getCurrentLocationIndex();
enterRoom(map.getLocationAt(playerLocation));
Scanner sc = new Scanner(System.in);
if(map.hasLeftChild(playerLocation)){
System.out.println ("Press 1 to go to " + map.getLocationAt(map.getLeftChild(playerLocation)).getName());
}
if(map.hasCenterChild(playerLocation)){
System.out.println ("Press 2 to go to " + map.getLocationAt(map.getCenterChild(playerLocation)).getName());
}
if(map.hasRightChild(playerLocation)){
System.out.println ("Press 3 to go to " + map.getLocationAt(map.getRightChild(playerLocation)).getName());
}
if(map.hasParent(playerLocation)){
System.out.println("Press 4 to go back to " + map.getLocationAt(map.getParent(playerLocation)).getName());
}
int choice = sc.nextInt();
sc.nextLine();
System.out.println("You picked " + choice);
super.takeTurn(choice);
}'
Any help is appreciated!

Related

While Loop Error Is Repeating My User Input Prompt

My goal in this project is to be able to ask a user if they want to add a mechanic and bay number to their respective ArrayLists. My code works fine, but there is one annoying problem. When the while loop that starts all of the code over again runs, the prompt for if they would like to edit the schedule prints twice, once without allowing a user response. I realise there is a lot of code to read but I will print it all here, and the bug that I get every time. It would mean a lot if someone could take the time to tell me what I need to fix.
Code:
// Import packages and create main function
import java.util.Scanner;
import java.util.ArrayList;
public class schedule{
public static void main(String []args){
// Creates scanner and ArrayLists
Scanner scanner = new Scanner(System.in);
ArrayList<Integer> mechanics = new ArrayList<Integer>();
ArrayList<Integer> bays = new ArrayList<Integer>();
boolean edit = true;
while(edit == true){
edit = editSchedule(scanner);
// Runs AddorRemove or ends program based on user's previous choice
if(edit == true){
if(AddorRemove(scanner) == true){
add(scanner, mechanics, bays);
}
else{
remove(scanner, mechanics, bays);
}
}
else{
System.out.println("Have a nice day!");
}
}
}
// Asks user if they want to edit the schedule
public static boolean editSchedule(Scanner scanner){
String answer = "b";
while(!(answer.equals("y")) || answer.equals("n")){
System.out.print("Would you like to edit the schedule? (y/n): ");
answer = scanner.nextLine();
if(answer.equals("y") || answer.equals("n")){
break;
}
else{
System.out.println("Invalid response.");
}
}
if(answer.equals("y")){
return true;
}
else{
return false;
}
}
// Asks user if they want to add or remove an element
public static boolean AddorRemove(Scanner scanner){
String aor = "b";
while(!(aor.equals("a")) || aor.equals("r")){
System.out.print("Do you want to add or remove a mechanic and bay? (a/r): ");
aor = scanner.nextLine();
if(aor.equals("a") || aor.equals("r")){
break;
}
}
if(aor.equals("a")){
return true;
}
else{
return false;
}
}
// Checks to see that elements are not present already and adds element to the mechanic and bay ArrayLists
public static void add(Scanner scanner, ArrayList<Integer> mechanics, ArrayList<Integer> bays){
System.out.print("Enter the mechanic's ID number: ");
int mechanic = scanner.nextInt();
System.out.print("Enter the bay number: ");
int bay = scanner.nextInt();
boolean shouldAdd = true;
for(int i=0; i<=mechanics.size()-1; i++){
if(mechanic == mechanics.get(i)){
System.out.println("Mechanic " + mechanic + " is already booked.");
shouldAdd = false;
}
}
for(int j=0; j<=bays.size()-1; j++){
if(bay == bays.get(j)){
System.out.println("Bay " + bay + " is already booked.");
shouldAdd = false;
}
}
if(shouldAdd == true){
mechanics.add(mechanic);
bays.add(bay);
System.out.println("Mechanic " + mechanic + " booked for bay " + bay + ".");
}
else{
System.out.println("Could not book mechanic " + mechanic + " in bay " + bay + ".");
}
}
// Removes an element from the mechanic and bay ArrayLists
public static void remove(Scanner scanner, ArrayList<Integer> mechanics, ArrayList<Integer> bays){
System.out.println("remove");
}
}
That is the code so far. Don't worry about the remove function, as I haven't added anything to it yet. Mainly focus on the main function and the editSchedule function, which is where something goes wrong. I will now paste the problem I am having with the output.
Would you like to edit the schedule? (y/n): y
Do you want to add or remove a mechanic and bay? (a/r): a
Enter the mechanic's ID number: 1
Enter the bay number: 3
Mechanic 1 booked for bay 3.
Would you like to edit the schedule? (y/n): Invalid response.
Would you like to edit the schedule? (y/n):
All I want to know is what is making the code repeat the phrase "Would you like to edit the schedule? (y/n):" and then adding "Invalid response." If any of you need clarification or further explanation, please let me know. Thanks!
When you use scanner.nextInt() it doesn't complete the line. See this test as an illustration:
#Test
public void testScanner() {
Scanner scanner = new Scanner("1\n2\n3\n4\n");
System.out.println("nextLine: [" + scanner.nextLine() + "]");
System.out.println("nextInt: [" + scanner.nextInt() + "]");
System.out.println("nextLine: [" + scanner.nextLine() + "]");
System.out.println("nextLine: [" + scanner.nextLine() + "]");
}
It produces:
nextLine: [1]
nextInt: [2]
nextLine: []
nextLine: [3]
So after the add() method returns, you have a line ending that the scanner will read as a blank line. That gives you the Invalid response message.

Strange behavior in simple command line program [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 2 years ago.
I'm trying to create a Java guessing game, but the first part I'm working on is having issues and I would like some help.
The program first asks a user to input a number, then the program asks them to confirm whether their number is what they inputted.
If they enter yes to whether they inputted the correct number, it currently just outputs "bru".
If no is inputted then they re-enter the input number and the cycle will go on until the user correctly inputs their number and confirms it.
I'm trying to accomplish this with a while loop.
Unfortunately when I run the program everything works fine until I'm asked to enter yes or no to confirm my number. If I enter yes it still asks for me to re-enter the number.
But if I enter no and then I say no again confirming my number it gives me the output for when I confirm that I inputted the correct number.
import java.util.Scanner;
import java.util.Random;
public class Assignment6 {
public static void main(String args[]) {
Scanner input = new Scanner( System.in );
System.out.print ( "Please enter the upper bound of the secret number.");
int UpperBound = input.nextInt();
System.out.print ( "The UpperBound you entered is" + " " + UpperBound + "." + "Is that correct?" + "" + "If yes please enter yes, if not please enter no.");
String TrueOrFalse = input.next();
while (TrueOrFalse == "no" | TrueOrFalse == "No");
{
System.out.print ( "Please enter the new upper bound of the secret number.");
UpperBound = input.nextInt();
System.out.print ( "The UpperBound you entered is" + " " + UpperBound + "." + " " + "Is that correct. If yes please enter yes, if not please enter no.");
TrueOrFalse = input.next();
}
System.out.print ("Bru");
}
}
Replace
while (TrueOrFalse == "no" | TrueOrFalse == "No");
with
while(TrueOrFalse.equalsIgnoreCase("no"))
i.e. remove ; from the while
also if possible renamme ur variable TrueOrFalse
Your major problem is with ; and comparing String using equals and ==.
Also you need to check difference between nextInt() and nextLine()
Try below code, it will help you.
public static void main(String args[]) {
Scanner input = new Scanner( System.in );
System.out.print ( "Please enter the upper bound of the secret number.");
int UpperBound = Integer.valueOf(input.nextLine());
System.out.print ( "The UpperBound you entered is" + " " + UpperBound + "." + "Is that correct?" + "" + "If yes please enter yes, if not please enter no.");
String TrueOrFalse = input.nextLine();
while (TrueOrFalse.equalsIgnoreCase("no"))
{
System.out.print ( "Please enter the new upper bound of the secret number.");
UpperBound = Integer.valueOf(input.nextLine());
System.out.print ( "The UpperBound you entered is" + " " + UpperBound + "." + " " + "Is that correct. If yes please enter yes, if not please enter no.");
TrueOrFalse = input.nextLine();
}
System.out.print ("Bru");
}

IDE prints both lines before I can parse user's inputs

so I am currently having difficult trying to fix this. In short, I'm trying to create a banking application for a class. I'm writing a method to print and get user's inputs but the print lines print out both lines before I can get inputs. Here is my implementation.
boolean done = false;
while(!done) {
System.out.println("Welcome to Running Bank"
+ "\nWhat would you like to do?"
+ "\n1-Create Account"
+ "\n2-Log-In"
+ "\n3-Exit");
choice = scanner.nextInt();
switch(choice) {
case 1:
System.out.println("Input your username(No more than 15 characters: ");
Username = scanner.nextLine();
System.out.println("Input your password(Must be at least 8 characters and not over 24): ");
Password = scanner.nextLine();
}
}
}
What I expected it to do was to print out "Input your username" then after I get the user's input for it then to print the next line. However, what happening right now is that both lines get print before I can put in anything.
Thank you in advanced.
boolean done = false;
while(!done) {
System.out.println("Welcome to Running Bank"
+ "\nWhat would you like to do?"
+ "\n1-Create Account"
+ "\n2-Log-In"
+ "\n3-Exit");
choice = scanner.nextInt();
scanner.nextLine();
switch(choice) {
case 1:
System.out.println("Input your username(No more than 15 characters: ");
Username = scanner.nextLine();
System.out.println("Input your password(Must be at least 8 characters and not over 24): ");
Password = scanner.nextLine();
}
}
}
This should work now. I have added a scanner.nextLine() after inputing choice

After input, println prints nothing out

I am making a game and it prompts you for your name and after you type in your name it asks you to confirm it by typing "N" or "Y". After pressing N it doesn't print anything back out although it does take in input but doesn't prompt you to do so as it doesn't print anything else. Only Y works. I have tried everything but it doesn't work.
This is the code I have done to confirm the name:
private static void comfirmName() {
System.out.println("Is " + name + " your name?");
try {
Thread.sleep(1000);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
System.out.println("Y/N");
if (input.nextLine().toUpperCase().equals("Y")) {
System.out.println("There is something you should know...");
}
if (input.nextLine().toUpperCase().equals("N")) {
System.out.println("Enter your name:");
name = input.nextLine();
System.out.println("Is " + name + " your name?");
}
if (!input.nextLine().toUpperCase().equals("N") && !input.nextLine().toUpperCase().equals("Y")) {
System.out.println("Please enter Y or N");
}
}
This is the output:
Welcome to Enchanted Mage!
Here we will venture into the dangers of this planet!
First of all, you must tell me your name, venturer!
Type in your name:
ots wng
Hello there ots wng!
Is ots wng your name?
Y/N
n
otswng
nothing is hapening
ummm
Please enter Y or N
BUILD SUCCESSFUL
There are no errors but it is really annoying to get any output out.
Just add an input before entering the ifs, just like that:
String inputAnswer = input.nextLine().toUpperCase();
and to be cleaner, just change the input.nextLine inside the ifs to the variable you just created, like that:
if(inputAnswer.equals("Y")){
System.out.println("There is something you should know...");
}
I just tested that and it works. feel free to ask anything else!
Read only once the confirmation.
private static void comfirmName() {
System.out.println("Is " + name + " your name?");
System.out.println("Y/N");
String confirmation = input.nextLine().toUpperCase(); //Read only once the user confirmation
if (confirmation.equals("Y")) {
System.out.println("There is something you should know...");
}
if (confirmation.equals("N")) {
System.out.println("Enter your name:");
name = input.nextLine();
System.out.println("Is " + name + " your name?");
}
if (!confirmation.equals("N") && !confirmation.equals("Y")) {
System.out.println("Please enter Y or N");
}
}
Output
Is Dan your name?
Y/N
n
Enter your name:
Dan
Is Dan your name?

Do while loop not printing correctly after 1st loop

I am trying to do a do-while loop that makes the program iterate again after the user inputs "y" or "Y", but everytime i run the program, It prints out something like this:
Would you like to try again?
Enter Y for yes or N for no: [DrJava Input Box] (I enter y)
Are you a student? (no input box is shown, and it skips it)
Are you a member of staff or faculty? [DrJava Input Box] (i enter yes or no)
How many tickets do you need? [DrJava Input Box] (I enter an int, but it doesnt complete that part where it shows how many tickets sold or how much it costs)
Would you like to try again?
Enter Y for yes or N for no: [DrJava Input Box]
this is what my program looks like:
import java.util.Scanner;
public class Ticket
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
double ticketprice = 12.00;
double result;
double result2;
double result3;
char repeat;
String input;
String student;
String staff;
int ticket;
do
{
System.out.println("Are you a student?");
student = keyboard.nextLine();
System.out.println("Are you a member of staff or faculty?");
staff = keyboard.nextLine();
System.out.println("How many tickets do you need?");
ticket = keyboard.nextInt();
if(student.equals("yes"))
{
System.out.println("Here is your " + ticket + " tickets for $0.00");
}
if(staff.equals("yes"))
{
result = ticketprice * .85;
result2 = ticket * result;
System.out.printf("Here are your " + ticket + " tickets for $%.2f\n", result2);
}
if(student.equals("no") && staff.equals("no"))
{
result3 = ticket * ticketprice;
System.out.printf("Here are your " + ticket + " tickets, for $%.2f\n", result3);
}
System.out.println("Would you like to try again?");
System.out.print("Enter Y for yes or N for no: ");
input = keyboard.next();
repeat = input.charAt(0);
}
while(repeat == 'y' || repeat == 'Y');
}
}
i am a beginner to programming, so any help would be good. Thank you.
At the end of the loop you call next() to read the "try again" response. This reads the next token, but still leaves the line ending on the input stream.
Next time through the loop, when you call nextLine() to read the "are you a student" response, it simply reads the remainder of that line immediately.
The easiest solution is:
Use nextLine() instead of next() for your "try again" prompt, but then this means you'll have to take care of the line ending left by nextInt() in the "tickets" question, so then you'll also have to...
Use nextLine() instead of nextInt() for your "tickets" question, then use Integer.parseInt() to parse the string into an int.
An alternate option, since all your responses seem to be just single-word responses, is to use next()/nextInt() everywhere and not use nextLine() at all. The point is, when you mix the two, you have to be aware of how they interact.
The issue lies in this block of code:
System.out.println("Would you like to try again?");
System.out.print("Enter Y for yes or N for no: ");
input = keyboard.next();
repeat = input.charAt(0);
When you call keyboard.next(), it doesn't read the entire line, so when your program loops again, the next time you call keyboard.nextLine(), it takes in part of what you entered previously in the loop and it gets ahead of itself.
The best solution would be to add a keyboard.nextLine() after you call keyboard.next() so that the remainder of the line will be consumed and won't be left over to mess up future iterations of the loop.
So for example you could change it like this:
System.out.println("Would you like to try again?");
System.out.print("Enter Y for yes or N for no: ");
input = keyboard.next();
keyboard.nextLine();
repeat = input.charAt(0);

Categories