Okay so my code works, however if the user correctly guesses "blue", the line prints "you got the right color!". Then the code should end. However, it brings up another a k.next(); line. How can I prevent this?
If you do not understand, here is the code.
import java.util.Scanner;
public class BEassignment11
{
public static void main (String [] args)
{
Scanner k = new Scanner (System.in);
String color;
String again;
do
{
System.out.println ("Try to guess my favorite color!");
color = k.next();
if (color.equalsIgnoreCase ("blue"))
{
System.out.println ("You got the right color!");
}
else
System.out.println ("That is not the right color. Would you like to try again? Yes/No");
again = k.next();
}
while (again.equalsIgnoreCase ("yes"));
}
}
You can just break out of the loop with the "break" statement like this:
if (color.equalsIgnoreCase ("blue")){
System.out.println ("You got the right color!");
break;
}
You can use break following System.out.println ("You got the right color!"); within if statement at do..while loop.
Or define a variable before do..while loop, for example var boolFlag = false set variable to true within if statement boolFlag = true, include || boolFlag === true within while condition.
System.out.println.... is part of the else clause. You seem to be surprised that the line
again = k.next();
still gets executed even when the user gets the color correct. I suggest you change the else code to the following:
if (color.equalsIgnoreCase ("blue"))
{
System.out.println ("You got the right color!");
again = "No";
}
else
{
System.out.println ("That is not the right color. Would you like to try again? Yes/No");
again = k.next();
}
That will automatically tell the program not to run again if the user guesses correctly and will only read the user's answer for trying again if they answer incorrectly.
Related
//Code up
if (userinput.contains(help)) {
//Go on with the game
}
else {
System.out.println("Im sorry , couldnt understand that"); //here is where i want to go back up and
repeat the command
}
I tried almost everything a beginner would know and nothing , do while loops not working in my case (maybe you can find a way) , if i let the if like that the game closes if you get the wrong answer (something out of conttext) , some help would be great! Thx :D
You could use a 'Recursive' function (a function that calls itself).
So in this case, you could do something like:
public void getAndParseInput(){
String userInput = getUserInput() // Use whatever you're using to get input
if(userInput.contains(help)){
// If the user input contains whatever the help is (note: if you're looking for the specific word help, it needs to be in speech marks - "help").
continueWithGame...
}else{
System.out.println("Im sorry , couldnt understand that");
this.getAndParseInput();
}
}
You need to put that code inside a while loop and establish an exit condition.
boolean endGame = false;
/* Here read userinput */
While(!endGame) {
if (userinput.contains(help)) {
//Go on with the game
} else if(userinput.contains("quit"){
endGame = true;
} else {
System.out.println("Im sorry , couldnt understand that"); //here is where i want to go back up and
repeat the command
}
/* Here read userinput */
}
The Below code is similar to your code,reuse the code with appropriate changes as you required.
The code works as below.
1. Scans the input from the console
2. Compares the scanned input with the String "help"
3. If scanned input matches with help, then continue with the execution
4. Otherwise, if the user wants to continue then he can press the
letter 'C' and continues with the execution.
5. If user doesn't press 'C', then the control breaks the while loop
and comes out of the execution
public void executeGame() {
Scanner scanner = new Scanner(System.in);
String help = "help";
while(true) {
System.out.println("Enter the input for execution");
String input = scanner.nextLine();
if (input.contains(help)){
System.out.println("Continue execution");
} else {
System.out.println("Sorry Wrong input.. Would you like to continue press C");
input = scanner.nextLine();
if (input.equals("C")){
continue;
} else {
System.out.println("Sorry wrong input :"+input);
System.out.println("Hence Existing....");
System.exit(0);
}
}
}
}
I have two available options for a user to input, and what I am trying to accomplish is if the user does not enter either of the inputs the program will continuously ask them again until they enter a valid one. Here is the code right now
String userLIB = user_input.next();
if (userLIB.contentEquals(UBC.acro)){
printDetails(UBC);
} else {
if (userLIB.contentEquals(ORL.acro)){
printDetails(ORL);
} else {
while (!userLIB.contentEquals(UBC.acro) || !userLIB.contentEquals(ORL.acro)){
System.out.println("Invalid input");
break;
}
}
}
I have a break to keep the code from looping the "Invalid input" indefinetly but it just ends the program right now which isn't what I want to happen. Is there a way to make the program go back to the start of the if statement?
You're breaking your code when the Invalid input condition is met.
Do as following,
String userLIB = "";
do {
userLIB = user_input.next();
if (userLIB.contentEquals(UBC.acro)){
printDetails(UBC);
} else if (userLIB.contentEquals(ORL.acro)) {
printDetails(ORL);
} else {
System.out.println("Invalid input. Try again!");
}
} while (!userLIB.contentEquals(UBC.acro) || !userLIB.contentEquals(ORL.acro));
This, tries to get the only 2 possible inputs and terminate the loop.
Else will loop again and again, until the required input is provided.
I figured it out with the help of #Carcigenicate, I put a while loop outside of the whole code and then put a userLIB = user_input.next(); inside of the incorrect if statement. Also thanks to #Sridhar for giving an answer that also works
public void talk() {
String[] prompts = {"Describe to me in a sentence why this is a cool program.",
"Describe to me in a sentence how your day was.",
"Describe to me in a sentence what programming means to you.",
"Describe to me in a sentence why food is neccessary for humans."};
iramInLoop = true;
while(iramInLoop)
{
int i = new Random().nextInt(prompts.length);
System.out.println(prompts[i]);
String input = Raybot.getInput();
if(!checkPunc(input) && !checkCaps(input)){
System.out.println("Check your capitalization and your punctuation!");
}
else{
System.out.println("Great grammar keep it up! Do you want to try again?");
if(input.equals("yes")) continue;
else
{
iramInLoop = false;
Raybot.talkForever();//this exits the loop
}
}
}
}
I am having extreme trouble trying to restart my loop. So at the end of my code when the loop is done running I put a string which asks if the user wants to try again and if the user says yes I want it to go back to the beginning of the loop and do what the loop does again. However, every time I run it it goes to the end of the loop and doesn't even ask for an input.
I think you should be breaking out of the loop if the person guessed right, but then decided not to continue. In this case, your logic should be something like this:
while (true) {
int i = new Random().nextInt(prompts.length);
System.out.println(prompts[i]);
String input = Raybot.getInput();
if (!checkPunc(input) && !checkCaps(input)) {
System.out.println("Check your capitalization and your punctuation!");
}
else {
System.out.println("Great grammar keep it up! Do you want to try again?");
input = Raybot.getInput();
if (input.equals("no")) {
break;
}
}
}
// whatever this does, you intended for it happen after the loop terminates, so do it here
Raybot.talkForever();
You are missing to actually accept any input
maybe
System.out.println("Great grammar keep it up! Do you want to try again?");
input = Raybot.getInput();
change if(input.equals("yes")) continue;
to if(Raybot.getInput().equals("yes")) continue;
Ok, So when I run the code, after typing in no or anything that which is false, my program doesn't jump to the Else statement at the bottom (Outside of the nested if_Else statement) What am I doing wrong? I tried initiating it with else if (yes!=true) or Else (!yes), I mean you name it, including changing the initial arguments and imputing ( yes==true ^ no==true) however, defining another boolean variable to no and set to true as well!
import java.util.Scanner;
public class Flights
{
public static void main(String args[]){
String txt;
boolean yes=true;
Scanner type=new Scanner(System.in);
int days;
System.out.println("Is this a round trip? ");
txt=type.next();
if(yes==true){
System.out.println("How many days in advance do you plan to book your flight?: ");
days=type.nextInt();
if(days>180)
System.out.println("Error: Flights can't be booked for more than 180 days out");
else if( days<=180 && days>=14)
System.out.println("Your flight cost is: $275");
else if(days<14 && days>=7)
System.out.println(" Your flight cost is: $320");
else if(days<7)
System.out.println("Your flight cost is: $440");
}
else
{
System.out.println("Enter your discount code");
}
}
}
Well, you initiate the yes variable to true, and didn't update it whatsoever before you start the conditional statement where you compare the value of yes to true. That's the issue.
This is where you begin:
boolean yes=true;
and then you wait for user typing in, but do not update the yes value, instead, you go ahead and check it like this.
if(yes==true){
}
This results in the else statement will never be reached.
What you could do is, following this line:
txt=type.next();
You can update the value of the yes variable, something like this:
txt=type.next();
yes = (txt != null) && "yes".equals(txt.toLowerCase());
if(yes==true){
//...
} else {
}
Hope this helps.
For your program to make a decision based on the user input, you have to look at the value of txt.
Change your code to something like this:
yes = txt.equalsIgnoreCase("yes");
if (yes == true) {
...
} else {
...
}
Or even shorter:
if (txt.equalsIgnoreCase("yes")) {
...
} else {
...
}
Everything of my guessing game is alright, but when it gets to the part of asking the user if he/she wants to play again, it repeats the question twice. However I found out that if I change the input method from nextLine() to next(), it doesn't repeat the question. Why is that?
Here is the input and output:
I'm guessing a number between 1-10
What is your guess? 5
You were wrong. It was 3
Do you want to play again? (Y/N) Do you want to play again? (Y/N) n
Here is the code:(It is in Java)
The last do while loop block is the part where it asks the user if he/she wants to play again.
import java.util.Scanner;
public class GuessingGame
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
boolean keepPlaying = true;
System.out.println("Welcome to the Guessing Game!");
while (keepPlaying) {
boolean validInput = true;
int guess, number;
String answer;
number = (int) (Math.random() * 10) + 1;
System.out.println("I'm guessing a number between 1-10");
System.out.print("What is your guess? ");
do {
validInput = true;
guess = input.nextInt();
if (guess < 1 || guess > 10) {
validInput = false;
System.out.print("That is not a valid input, " +
"guess again: ");
}
} while(!validInput);
if (guess == number)
System.out.println("You guessed correct!");
if (guess != number)
System.out.println("You were wrong. It was " + number);
do {
validInput = true;
System.out.print("Do you want to play again? (Y/N) ");
answer = input.nextLine();
if (answer.equalsIgnoreCase("y"))
keepPlaying = true;
else if (answer.equalsIgnoreCase("n"))
keepPlaying = false;
else
validInput = false;
} while (!validInput);
}
}
}
In your do while loop, you don't want the nextLine(), you just want next().
So change this:
answer = input.nextLine();
to this:
answer = input.next();
Note, as others have suggested, you could convert this to a while loop. The reason for this is that do while loops are used when you need to execute a loop at least once, but you don't know how often you need to execute it. Whilst it's certainly doable in this case, something like this would suffice:
System.out.println("Do you want to play again? (Y/N) ");
answer = input.next();
while (!answer.equalsIgnoreCase("y") && !answer.equalsIgnoreCase("n")) {
System.out.println("That is not valid input. Please enter again");
answer = input.next();
}
if (answer.equalsIgnoreCase("n"))
keepPlaying = false;
The while loop keeps looping as long as "y" or "n" (ignoring case) isn't entered. As soon as it is, the loop ends. The if conditional changes the keepPlaying value if necessary, otherwise nothing happens and your outer while loop executes again (thus restarting the program).
Edit: This explains WHY your original code didn't work
I should add, the reason your original statement didn't work was because of your first do while loop. In it, you use:
guess = input.nextInt();
This reads the number off the line, but not the return of the line, meaning when you use:
answer = input.nextLine();
It immediately detects the leftover carriage from the nextInt() statement. If you don't want to use my solution of reading just next() you could swallow that leftover by doing this:
guess = input.nextInt();
input.nextLine();
rest of code as normal...
The problem really lies in a completely different segment of code. When in the previous loop guess = input.nextInt(); is executed, it leaves a newline in the input. Then, when answer = input.nextLine(); is executed in the second loop, there already is a newline waiting to be read and it returns an empty String, which activates the final else and validInput = false; is executed, to repeat the loop (and the question).
One solution is to add an input.nextLine(); before the second loop. Another is to read guess with nextLine() and then parse it into an int. But this complicates things as the input could not be a correct int. On a second thought, the code already presents this issue. Try entering a non-numeric response. So, define a function
public static int safeParseInt(String str) {
int result;
try {
result= Integer.parseInt(str) ;
} catch(NumberFormatException ex) {
result= -1 ;
}
return result ;
}
And then replace your first loop with:
do {
validInput= true ;
int guess= safeParseInt( input.nextLine() ) ;
if( guess < 1 || guess > 10 ) {
validInput= false ;
System.out.print("That is not a valid input, guess again: ");
}
} while( !validInput );
PS: I don't see any problem with do-while loops. They are part of the language, and the syntax clearly indicates that the condition is evaluated after the body is executed at least one time. We don't need to remove useful parts of the language (at least from practice) just because others could not know them. On the contrary: if we do use them, they will get better known!
validInput = false;
do {
System.out.print("Do you want to play again? (Y/N) ");
answer = input.next();
if(answer.equalsIgnoreCase("y")){
keepPlaying = true;
validInput = true;
} else if(answer.equalsIgnoreCase("n")) {
keepPlaying = false;
validInput = true;
}
} while(!validInput);
I changed the coding style as I find this way more readable.
Your problem is that nextInt will stop as soon as the int ends, but leaves the newline in the input buffer. To make your code correctly read the answer, you'd have to enter it on the same line as your guess, like 5SpaceYReturn.
To make it behave more than one would expect, ignore the first nextLine result if it contains only whitespace, and just call nextLine again in that case without printing a message.
I believe the output of input.nextLine() will include the newline character at the end of the line, whereas input.next() will not (but the Scanner will stay on the same line). This means the output is never equal to "y" or "n". Try trimming the result:
answer = input.nextLine().trim();