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");
}
Related
I am brand new to coding and trying to get my second program working. It is pretty straight forward as to what it does, but it is throwing an error on line 24 "Duplicate local variable confirm". Can't quite work out why it doesn't like what I'm doing.
Scanner userInput = new Scanner(System.in);
char confirm;
do{
System.out.println("Welcome to the story teller");
System.out.println("What is your name?");
String name = userInput.nextLine();
System.out.println("How old are you?");
int age = userInput.nextInt();
System.out.println("What country would you like to visit?");
String country = userInput.nextLine();
System.out.println("Great! So your name is" + name + ", you are" + age + "years old and you would like to visit" + country + "?");
System.out.println("Press Y to continue or N to start over");
char confirm = userInput.next().charAt(0);
if (confirm !='y' || confirm !='n'){
System.out.println("Sorry that input is not valid, please try again");
}
else {
System.out.println(name + "landed in" + country + "at the age of" + age + ".");
}
} while(confirm == 'Y'|| confirm == 'y');
You're declaring confirm twice. Change the second declaration to just assigning to it and you should be OK:
confirm = userInput.next().charAt(0);
// No datatype, so you aren't declaring confirm, just assigning to it
Because your "confirm" variable already defined in the scope (second row). If you want to assign a value, just write confirm = userInput.next().charAt(0);
Another option to fix is to remove the unnecessary declaration char confirm;
And use it only when needed
char confirm = userInput.next().charAt(0);
As #ScaryWombat suggested, you will need to change scope of the variable (currently while is in different scope than do )
It seems apart from re-declaration of the variable confirm there are one or more issue -
Issue 1:
After int age = userInput.nextInt(). It won't prompt for country input and will prompt Press Y to continue or N to start over.
Cause of this issue:
Since you are using int age = userInput.nextInt(); the scanner will only take the integer value from the input and will skip the \n newline character.
Fix
As a workaround, I've added userInput.nextLine(); after int age = userInput.nextInt(); such that it will consume the \n character after nextInt().
Issue 2:
After the 1'st iteration, this line will cause issueconfirm = userInput.next().charAt(0);.
Cause of this issue:
In 2'nd iteration you won't get a prompt to enter the name as the line String name = userInput.nextLine(); will take \n from the last iteration as input and will skip and prompt for age How old are you?.
Fix
As a workaround, I've added userInput.nextLine(); after confirm = userInput.next().charAt(0); such that it will consume the \n character after userInput.next().charAt(0) and the next iteration will go as expected.
Issue 3:
This logic if (confirm !='y' || confirm !='n') expects only y and n in lowercase but here while(confirm == 'Y'|| confirm == 'y') you are expection y and Y both.
Fix - I've added the necessary changes in the code below but would recommend you do change it to a switch case.
NOTE:
It is not recommended to do userInput.nextLine() after every input and you could simply parse it. See here for further information.
I'm not recommending it but this will get you program working
Scanner userInput = new Scanner(System.in);
char confirm;
do {
System.out.println("Welcome to the story teller");
System.out.println("What is your name?");
String name = userInput.nextLine();
System.out.println("How old are you?");
int age = userInput.nextInt();
userInput.nextLine(); //adding this to retrieve the \n from nextint()
System.out.println("What country would you like to visit?");
String country = userInput.nextLine();
System.out.println("Great! So your name is " + name + ", you are " + age
+ "years old and you would like to visit " + country + " ?");
System.out.println("Press Y to continue or N to start over");
confirm = userInput.next().charAt(0);
userInput.nextLine(); //adding this to retrieve the \n this will help in next iteration
System.out.println(name + " landed in " + country + " at the age of " + age + ".");
if (confirm == 'y' || confirm == 'Y') {
continue; // keep executing, won't break the loop
} else if (confirm == 'n' || confirm == 'N') {
break; // breaks the loop and program exits.
} else {
System.out.println("Sorry that input is not valid, please try again");
// the program will exit
}
} while (confirm == 'Y' || confirm == 'y');
}
Recommending that you use switch case instead of if comparasion of confirmation and parse the character and integer input and remove the arbitary userInput.nextLine() added as workaround.
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!
My program basically allows the user to enter grades (elements) which are stored in a Gradebook (array). The user also has the option to change the grades (elements) in the Gradebook (array).
My issue is that once the while loop loops and the user is asked "Make more changes? Enter Yes or No" If I enter yes, then the user asked which grade to change, is allowed to replace the grade, and the modified gradebook prints. However, if I enter "no" just the gradebook prints. Is there a way I can get the program to print "Good bye!" (signaling the end of the program) if the user enters no? I believe I'm supposed reorganize my code and set a while-loop with boolean = false? But I'm not sure how to get started...
Any help would be greatly appreciated. Thank you.
System.out.println("Make changes? Enter Yes or No");
String makeChanges = input.next();
if (makeChanges.equals("no")) {
System.out.println("Good bye!");
}
while (makeChanges.equalsIgnoreCase("Yes")) {
// Ask user if what grade they would like to change
//int index = NumberReader.readPositiveInt(input, "Enter the index of the grade to be changed: (1 to " + grades + ") : ", "Invalid index input", index);
int index = NumberReader.readCappedPositiveInt(input, "Enter the index of the grade to be changed: (1 to " + grades + ") : ", "Invalid index input", numOfGrades);
System.out.println("Enter grade (limit to two decimal places)" + ": ");
// offset the index by one
mogrades[index - 1] = NumberReader.readPositiveDouble(input, "Enter grade " + index + " :",
"Invalid data entered");
System.out.println("The Grade book contains: ");
printArray(mogrades);
System.out.println("Make more changes? Enter Yes or No");
makeChanges = input.next();
System.out.println(makeChanges);
System.out.println("The Grade book contains: ");
printArray(mogrades);
}
}
Break statements are used to exit loops. You could try this in the while loop:
if (makeChanges.equalsIgnoreCase("No")) {
System.out.println("Good Bye!");
break;
}
If you want to exit the entire program, use System.exit(0);
if (makeChanges.equalsIgnoreCase("No")) {
System.out.println("Good Bye!");
System.exit(0);
}
Here is a simple program demonstrating how this would work:
import java.util.Scanner;
public class Simple {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String makeChanges = "Yes";
while (makeChanges.equalsIgnoreCase("Yes")) {
System.out.println("Make more changes? Enter Yes or No:");
makeChanges = input.next();
if (makeChanges.equalsIgnoreCase("No")) {
System.out.println("Good Bye!");
System.exit(0);
}
}
}
}
And here is the output from the command line:
daniel#4.3:StackOverflow$ javac Simple.java
daniel#4.3:StackOverflow$ java Simple
Make more changes? Enter Yes or No:
Yes
Make more changes? Enter Yes or No:
Yes
Make more changes? Enter Yes or No:
No
Good Bye!
I'm creating a program to call another code that creates an RPN Calculator
RPNCalculator Calculator = new RPNCalculator();
System.out.println("Please enter a valid post-fix expression one token " +
"at a time with a space between each token (e.g. 5 4 + 3 2 1 - + *)");
System.out.println("Each token must be an integer or an operator (+,-,*,/)");
Scanner reader= new Scanner(System.in);
System.out.println();
System.out.println("That expression equals " + result);
System.out.println();
while (true)
{
equation = reader.nextLine();
result=Calculator.evaluateEquation(equation);
}
However when the program runs, it does not even give the chance to input anything and will return "That expression equals 0"
You have your while loop on the wrong side of the System.out.println()'s.
Scanner reader= new Scanner(System.in);
while (true)
{
equation = reader.nextLine();
//YOU ALSO need a reason to break out of this loop.
//LIKE IF equation == "EXIT" or "0"
//BREAK
result=Calculator.evaluateEquation(equation);
}
System.out.println();
System.out.println("That expression equals " + result);
System.out.println();
System.out.print("Price of the book? ");
while (!keyboard.hasNextDouble() || priceOfBook <=0)
{
System.err.print("Invalid input - Price of " + bookTitle + "? ");
keyboard.nextLine();
}
priceOfBook = keyboard.nextDouble();
I am trying to validate the above code basically so that user can't enter negative numbers or letters or empty doubles but it's not working and I can't see where I'm going wrong. Can someone please help me?
So how i understand you need to real line until the user didint enter negative or letter.
Scanner sc = new Scanner(System.in);
double x = 0;
System.out.println("Enter price");
while (true) {
if (!sc.hasNextDouble()) {
System.out.println("Sorry price cant be negative or be letter");
break;
}
System.out.println("Enter price");
x = sc.nextDouble();
}
Hope it helps!
You put
priceOfBook = keyboard.nextDouble();
outside of your while loop :) Try like this:
while (priceOfBook <= 0)
{
System.err.print("Invalid input - Price of " + bookTitle + "? ");
priceOfBook = keyboard.nextDouble();
}
So that it will keep asking the user if he enters a number < 0.
You don't assign the user's input to priceOfBook until after the while loop. So, when your loop checks if priceOfBook is negative, it doesn't check the user's input, but the previously stored value (if there is one). This allows the user's input (even if it's negative) to pass the while loop, and then get saved as priceOfBook.
Try instead:
while (!keyboard.hasNextDouble() || priceOfBook = keyboard.nextDouble() <=0) {
System.err.print("Invalid input - Price of " + bookTitle + "? ");
keyboard.nextLine();
}