The code is for multiple choice question. If the answer is incorrect, the user should try until they find the right answer. When the answer is correct, there is no problem, but if it is wrong then it gets stuck, and it is keep saying "Your answer is incorrect!". What should I do?
import java.util.*;
public class Question {
public static void main(String[] args) {
System.out.println();
System.out.println("Question 1");
System.out.println();
System.out.println("What is 2+2?");
System.out.println("A. 2");
System.out.println("B. 4");
System.out.println("C. 6");
System.out.println("D. 8");
Scanner input = new Scanner(System.in);
char getAnswerFromUser = input.next().charAt(0);
char answer = 'B';
boolean isAnswerTrue = false;
while(!isAnswerTrue) {
if(getAnswerFromUser == answer ) {
System.out.println("Your answer is correct!");
isAnswerTrue = true;
} else{
System.out.println("Your answer is incorrect!");
isAnswerTrue = false;
}
}
}
}
You are not actually getting a new answer from the user inside your loop. You are only getting it once, in the line where you define the variable getAnswerFromUser. You need to actually get a new answer. I suggest putting it into a separate method to keep that step clean from the step where you use that answer.
Related
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 months ago.
Improve this question
My program proceeds to the else statement even though the user inputs the correct answer and the if statement is run.
package dowhileloops;
import java.util.Scanner;
public class DoWhileLoops {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
String res, ans;
System.out.println("=========================================");
System.out.println(" **** Do-While Loops **** ");
System.out.println("=========================================\n");
do{
System.out.println("What is the color of the ocean?");
System.out.println("\nA.) Orange\n\nB.) Green\n\nC.) Blue\n\nD.) Yellow\n\n");
System.out.print("Enter your answer: ");
res = in.nextLine();
if (res.equalsIgnoreCase("C"))
System.out.println("You are correct!");
else
System.out.println("You are wrong!");
System.out.println("Would you like to try again? (Yes/No)");
ans = in.nextLine();
}while(ans.equalsIgnoreCase("Yes"));
}
}
It proceeds to execute the line
System.out.println("Would you like to try again? (Yes/No)"); ans = in.nextLine(); even though it should stop at System.out.println("You are correct!");
I want the program to terminate after the user types the correct answer "C"
It is happening because you did not put curly brackest { and }.
Here is the code with the curly brackets.
package dowhileloops;
import java.util.Scanner;
public class DoWhileLoops {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String res, ans;
System.out.println("=========================================");
System.out.println(" **** Do-While Loops **** ");
System.out.println("=========================================\n");
do {
System.out.println("What is the color of the ocean?");
System.out.println("\nA.) Orange\n\nB.) Green\n\nC.) Blue\n\nD.) Yellow\n\n");
System.out.print("Enter your answer: ");
res = in.nextLine();
if (res.equalsIgnoreCase("C"))
System.out.println("You are correct!");
else {
System.out.println("You are wrong!");
System.out.println("Would you like to try again? (Yes/No)");
ans = in.nextLine();
}
} while (ans.equalsIgnoreCase("Yes"));
}
}
========
Edit #1:
It is not the optimum solution, but it works. I tried to run your code correctly with the minimum amount of editing
package dowhileloops;
import java.util.Scanner;
public class DoWhileLoops {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String res, ans;
System.out.println("=========================================");
System.out.println(" **** Do-While Loops **** ");
System.out.println("=========================================\n");
do {
System.out.println("What is the color of the ocean?");
System.out.println("\nA.) Orange\n\nB.) Green\n\nC.) Blue\n\nD.) Yellow\n\n");
System.out.print("Enter your answer: ");
res = in.nextLine();
if (res.equalsIgnoreCase("C")) {
System.out.println("You are correct!");
ans = "No";
} else {
System.out.println("You are wrong!");
System.out.println("Would you like to try again? (Yes/No)");
ans = in.nextLine();
}
} while (ans.equalsIgnoreCase("Yes"));
}
}
You should accept the char not the string.
res = in.nextLine().charAt(0);
this will accept the first char no matter the rest of the chars.
and use curly brace after for else statement.
As with your do...while loop, the if and the else should have their content wrapped in curly braces to clearly show the compiler which parts of the code are relevant to the respective if/else.
package dowhileloops;
import java.util.Scanner;
public class DoWhileLoops {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
String res, ans;
System.out.println("=========================================");
System.out.println(" **** Do-While Loops **** ");
System.out.println("=========================================\n");
do{
System.out.println("What is the color of the ocean?");
System.out.println("\nA.) Orange\n\nB.) Green\n\nC.) Blue\n\nD.) Yellow\n\n");
System.out.print("Enter your answer: ");
res = in.nextLine();
if (res.equalsIgnoreCase("C")) {
System.out.println("You are correct!");
}
else {
System.out.println("You are wrong!");
System.out.println("Would you like to try again? (Yes/No)");
ans = in.nextLine();
}
}while(ans.equalsIgnoreCase("Yes"));
}
}
Without a curly brace, the compiler will assume that only the very next line is needed for the else, and the end result looks something like the following:
if (res.equalsIgnoreCase("C")) {
System.out.println("You are correct!");
}
else {
System.out.println("You are wrong!");
}
System.out.println("Would you like to try again? (Yes/No)");
ans = in.nextLine();
The 'would you like to try again', and 'ans = in.nextLine()' are placed outside the else, hence the result you are getting.
I have a program where the user is asked multiple choice questions and one of the choices to every question is to exit.
If exit is chosen, I then have to ask whether user wants to start again, if yes, I want to loop back to a certain checkpoint. If not, the program terminates.
Below is a simplified sample with only one question. The program I'm trying to build has multiple.
Is there a way that does not involve nested loop upon nested loops upon nested loops?
import java.util.Scanner;
class RandomStuff {
/* this is not the actual program, just a simplified version to show what I'm trying to figure out
let's pretend perfect input
*/
public static void main (String[]args){
Scanner keyboard = new Scanner(System.in);
// checkpoint I wish to loop back to. Not the beginning of the program
System.out.println("Press 1 to continue, press 2 to cancel ");
int number = keyboard.nextInt();
String again;
switch(number){
case 1:
System.out.println("user chose to continue");
break;
case 2:
System.out.println("user chose to cancel");
System.out.println("start again? (yes/no)");
again = keyboard.next();
if("yes".equals(again)){
/* loop to checkpoint*/ }
else
System.exit(0);
break;
}
/* afterwards, a few other rounds of asking an input an looping to the same checkpoint
when appropriate. Essentially I'm looking for a method to loop back to checkpoint
from any decision to be made
*/
keyboard.close();
}
}
Use of recursive functions is the best alternative for loops. Instead of writing your choices in the main method you can use anther method like below:
import java.util.Scanner;
class Random{
public static void Choice(Scanner keyboard){
System.out.println("Press 1 to continue, press 2 to cancel ");
int number = keyboard.nextInt();
String again;
switch(number){
case 1:
System.out.println("user chose to continue");
break;
case 2:
System.out.println("user chose to cancel");
System.out.println("start again? (yes/no)");
again = keyboard.next();
if("yes".equals(again)){
Choice(keyboard);
//Function will be called again
}
else
System.exit(0);
break;
}
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
Choice(sc);
}
}
But this can also easily be done with the use of a single do-while loop
See this:
import java.util.Scanner;
class Random{
public static void main(String args[]){
Scanner keyboard = new Scanner(System.in);
boolean run = true;
do{
System.out.println("Press 1 to continue, press 2 to cancel ");
int number = keyboard.nextInt();
String again;
switch(number){
case 1:
System.out.println("user chose to continue");
break;
case 2:
System.out.println("user chose to cancel");
System.out.println("start again? (yes/no)");
again = keyboard.next();
if("yes".equals(again)){
continue;
}
else
run = false;
//terimanting the loop
break;
}
}
while(run);{
System.out.println("User chose to exit");
System.exit(0);
}
}
}
I tested both the programs and they run fine on my end, if you have any problem or you can't understand something, just tell me.
I'm working on an assignment and I mostly have it finished but I am having an issue with the last method. I'm trying to write a continueGame() method that will ask the user if they want to continue to play, and accept "y" or "n". If answered "y", the program starts again. If answered "n", the program stops and a message is shown. The problem is I need it to trigger the continueGame() method only when userChoice == answer. This is a number guessing game with an object oriented approach.
I've tried to call the continueGame() method inside my else if(userChoice == answer) statement but it doesn't seem to work. Even when my other if/else if statements are triggered, it continues to the continueGame() method.
Here is the main driver for the game
import java.util.Scanner;
public class NumberGame
{
public static void main(String[] args)
{
Scanner input = new Scanner (System.in);
GameOptions opt = new GameOptions(); // Your created class
int userChoice = -1234;
int answer = -1234;
boolean keepPlaying = true;
System.out.println("Guess the Number Game\n");
while (keepPlaying == true) {
answer = (int) (Math.random() * 10)+1;
//Create a getChoice method in your class and make sure it accepts a Scanner argument
userChoice = opt.getChoice(input);
//Create a checkAnswer method in your class. Make sure it accepts two integer arguments and a Scanner argument
opt.checkAnswer(userChoice, answer, input);
// Create a continueGame method in your class and make sure it accepts a Scanner argument
keepPlaying = opt.continueGame(input);
}
System.out.println("Thanks for playing.");
}
}
Here is the class that I am working on for the methods. Note that I can not make any modifications to the main driver file.
import java.util.InputMismatchException;
import java.util.Scanner;
import java.lang.NumberFormatException;
public class GameOptions {
int count = 0;
boolean cont = true;
//getChoice Method for NumberGame
public int getChoice(Scanner scnr) {
System.out.println("Please choose a number between 1 and 10: ");
int userGuess = 0;
String input = scnr.next();
try {
userGuess = Integer.parseInt(input);
if (userGuess < 1 || userGuess > 10) {
throw new IllegalArgumentException("Invalid value. Please enter a number between 1 and 10: ");
}
}
catch(NumberFormatException e) {
System.out.println("Error - Enter Numerical Values Only");
return userGuess;
}
catch (IllegalArgumentException ex) {
System.out.println(ex.getMessage());
}
return Integer.parseInt(input);
}
public void checkAnswer(int userChoice, int answer, Scanner scnr) {
if (userChoice > answer && userChoice < 11) {
System.out.println("Too high. Try again.");
count++;
} else if (userChoice < answer && userChoice > 0) {
System.out.println("Too low. Try again.");
count++;
} else if (userChoice == answer) {
System.out.println("You got it! Number of tries: " + count);
System.out.println("Would you like to play again? (y/n)");
}
}
public static boolean continueGame(Scanner scnr) {
String input = scnr.nextLine();
if (input.toLowerCase().equals("y")){
return true;
} else if (input.toLowerCase().equals("n")){
return false;
} else {
System.out.println("Invalid entry. Please enter either y or n: ");
return continueGame(scnr);
}
}
}
So I should be able to enter a number, and if its lower than the answer it will tell me I am too low, if its higher than the answer it will tell me that its too high, if its equal it will tell me I won and prompt me to press "y" or "n" if I want to continue. Another issue I am running into is that I am getting "Would you like to play again? (y/n)" no matter whether I guess the right number or not and my only option is to hit "y" or "n"
The driver class is calling continueGame() inside the while loop. If you're not allowed to modify that class then presumably asking at every iteration is the intended behaviour.
You should move System.out.println("Would you like to play again? (y/n)"); into the continueGame() method so that it only asks when that method is called.
The way the driver is written (I guess) is coming from your instructor/lecturer/professor, right?
With the driver (as it is), you don't need to call continueGame method from checkAnswer method. The driver is going to call it.
Just run the driver and it will work. If you have a proper IDE (eclipse or Netbeans), trace through and see what the input accepted is (I think there is line-feed in the accepted answer).
Try this (I just changed the loop structure; yours is also valid):
public static boolean continueGame(Scanner scnr) {
while (true) {
String input = scnr.nextLine().trim(); // to remove white spaces and line-feed
if (input.toLowerCase().equals("y")){
return true;
} else if (input.toLowerCase().equals("n")){
return false;
} else {
System.out.println("Invalid entry. Please enter either y or n: ");
}
}
}
Added for checkAnswer method to keep the user guess the answer until he gets correct:
public static checkAnswer(/*three arguments*/) {
boolean correct = false;
while (! correct) {
// accept input
if (answer.equals(input)) {
correct = true;
// print required correct/congrats messages here
} else {
// print required input/try again messages here
}
}
// print would you like to play again with new answer y/n message here.
}
In my opinion, printing "play again with new answer y/n message" should go into continueGame method (from last portion of checkAnswer) method to stick to encapsulation concepts.
I'm currently developing a math game for elementary students and I'm trying to let the user continuously enter an answer until they get the question correct. Then I want them to move onto the next question. When I run the code below it gives me 2 chances to enter the correct answer but it wont show my 'Correct' message after the second time.
import java.util.Scanner;
public class test{
public static void main (String[]args){
Scanner kb= new Scanner(System.in);
double r5q1,r5q2,r5q3,r5q4,r5q5;
System.out.println("Welcome to the money level.. This is the last and most difficult level!");
//Question 1
System.out.println("Question 1: I have $10.00 and I buy a candy bar for $3.00. How much change will I get?");
r5q1=kb.nextDouble();
if(r5q1==7)
System.out.println("Correct!");
else
System.out.println("Try again!");
r5q1=kb.nextDouble();
}
}
This is a photo of my code
Put your input taking code inside do while loop and in while condition check for correct output
do{
statements(s)
}while(condition);
try this.
import java.util.Scanner;
public class Main
{
public static void main (String[] args)
{
Scanner cin = new Scanner(System.in);
int ans = 123;
do {
System.out.println("Your question here.\n");
} while (cin.nextInt() != ans);
System.out.println("correct!\n");
}
}
while(userAnswer != realAnswer){
System.out.print("Wrong answer. Try again: ");
userAnswer = in.nextInt(); // or whatever you need instead of int
}
You have to use a while loop. This loop repeats its "contents" (the code inside the curly brackets) while its condition (the boolean value inside the normal brackets) is true. In this case, the condition is that the input is incorrect and the "content" is the code which prints the "Try again!" message.
Here's a demonstration:
Scanner scanner = new Scanner(System.in);
while (scanner.nextDouble() != 7) {
System.out.println("Try again!");
}
System.out.println("Correct!");
declare a flag value. And initially set it to 0. flag=0;
do{
if(r5q1==7){
flag=1;
break;
}
else{
continue;
}
}while(r5q1!=7);
if(flag==1)
{
System.out.println("Correct");
}
else
{
System.out.println("Wrong");
}
Thanks admin! That worked very well!
import java.util.Scanner;
public class test{
public static void main (String[]args){
Scanner kb= new Scanner(System.in);
double r5q1,r5q2,r5q3,r5q4,r5q5;
System.out.println("Welcome to the money level.. This is the last and most difficult level!");
//Question 1
System.out.println("Question 1: I have $10.00 and I buy a candy bar for $3.00. How much change will I get?");
r5q1=kb.nextDouble();
do{
System.out.println("Try again!");
r5q1=kb.nextDouble();
}while(r5q1!=7);//This is the answer to the question
System.out.println("Correct!");
//Question 2
System.out.println("Question 2: I have $15.00 and I buy 5 apples for $1.00 each. How much change will I get?");
r5q1=kb.nextDouble();
do{
System.out.println("Try again!");
r5q2=kb.nextDouble();
}while(r5q2!=10); //This is the answer to the question
System.out.println("Correct!");
}
}
I am trying to make a simple text adventure game in Java and when I type Quit it ends the game. But instead it will ask if you want to do the quest even if you type quit which is suppose to end the code, I tried using loops to fix this error but had to luck. Any idea where I went wrong?
import java.util.*;
public class TextGame {
public static void main(String[] args) {
//Boolean run = true;
//while (run){
Scanner in = new Scanner(System. in );
System.out.println("~SPECTRE~");
System.out.println("");
System.out.println("Please Choose One Below");
System.out.println("");
System.out.println("New");
System.out.println("Quit");
System.out.println("");
String option;
System.out.print("Select one of the options here: ");
option = in .next();
if (option.equals("New")) {
System.out.println("Hello adventurer! Welcome to the land of Spectre.");
String name;
System.out.print("What is your name adventurer? ");
name = in .next();
System.out.println("Hello there! " + name);
} else if (option.equals("Quit")) {
System.out.println("*Returns to desktop*");
}
String quest;
System.out.print("Would you like to go on a quest? ");
quest = in .next();
if (quest.equals("Yes")) {
System.out.println("Here is a list of quests that I would like you to do ");
System.out.println("");
System.out.println("1) Fight the evil troll of Port Howlham");
System.out.println("");
System.out.println("2) Deliver supplys to the soliders in need");
System.out.println("");
System.out.println("3) Find the Kings lost son");
System.out.println("");
System.out.println("4) Find the Gemstone of Darlingbee to defeat the evil witch of Hobbitstone");
} else {
option.equals("");
System.out.println("*Please pick New Game or Quit*");
}
}
}
try this:
} else if (option.equalsIgnoreCase("Quit")) {
System.exit(0);
}
Or this:
} else if (option.equalsIgnoreCase("Quit")) {
return;
}
You're probably looking to exit the program. Use System.exit(0);
else if(option.equals("Quit"))
{
System.exit(0);
}
The 0 argument is a status code that indicates normal termination of the program.
You can use System.exit(code) to finish the program. Put this at the end of the else if block:
if (option.equals("Quit") {
...
System.exit(0);
}
The code can be any integer:
The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination.