Im looking to make this loop after it asks them a question in this case ""What is 2+2?" then taking there input, Then the program should ask "Are you sure Y/N" if they awnser no i want it to go back to the start of this loop and allow them to redo the question. As it is i can't get this to loop and after this part works i will need to do 9 more questions in the same format
import java.util.Scanner;
class Quiz
{
public static void main (String[] args)
{
int q1=0 , q2=0;
boolean correct = false;
char yn1='y';
String q3 , q4;
Scanner input1 = new Scanner( System.in );
int count = 0 ;
//Question 1 start
while (correct == false)
{
System.out.println("What is 2+2? ");
System.out.println("Choices: 0,2,4,8");
q1 = input1.nextInt(); //used after loop
System.out.println("Are You Sure? (y/n)");
char c = input1.next().charAt(0); // Changed LINE
if (c=='y') // Changed LINE
{
if ( q1 == 4) //q1 was stated during loop
System.out.println("You were correct 2+2 = 4");
else
System.out.println("You were wrong");
break;
}
}
//Question 2 start
while (correct == false)
{
System.out.println("how many legs does a legless cow have?");
System.out.println("Choices: 0,25,4,31");
q2 = input1.nextInt();
System.out.println("Are You Sure? (y/n)");
char c = input1.next().charAt(0);
if (c=='y')
{
if ( q2 == 0)
System.out.println("You were correct, the cow has 0 legs");
else
System.out.println("You were wrong");
break;
}
}
//Question 3 start
while (correct == false)
{
System.out.println("What is the capital city of Canada?");
System.out.println("Choices: Toronto, Montreal, Vancouver, Ottawa (capitals count)");
q3 = input1.nextLine();
System.out.println("Are You Sure? (y/n)");
char c = input1.next().charAt(0);
if (c=='y')
{
if ( "Ottawa".equals(q3))
System.out.println("You were correct, The capital is Ottawa");
else
System.out.println("You were wrong");
break;
}
}
}
}
A new problem has occurred i have used the one helpful example and may try to change it to an array later but not in till i get the basics working. all the Questions usings int work so far Ie.
//Question 1 start
while (correct == false)
{
System.out.println("What is 2+2? ");
System.out.println("Choices: 0,2,4,8");
q1 = input1.nextInt(); //used after loop
System.out.println("Are You Sure? (y/n)");
char c = input1.next().charAt(0); // Changed LINE
if (c=='y') // Changed LINE
{
if ( q1 == 4) //q1 was stated during loop
System.out.println("You were correct 2+2 = 4");
else
System.out.println("You were wrong");
break;
}
}
But now i want to use a word awnser so i made a string and put it in instead of int but now instead of allowing input for q3 it skips to input of y/n i don't understand why all of a sudden it would do this yet the other questions work correctly with int.
while (correct == false)
{
System.out.println("What is the capital city of Canada?");
System.out.println("Choices: Toronto, Montreal, Vancouver, Ottawa (capitals count)");
String q3 = input1.nextLine();
System.out.println("Are You Sure? (y/n)");
char c = input1.next().charAt(0);
if (c=='y')
{
if ( "Ottawa".equals(q3))
System.out.println("You were correct, The capital is Ottawa");
else
System.out.println("You were wrong");
break;
}
}
Im sorry if this hasn't been enough detail or is formated wrong and will be sure to fix it if it is.
When reading input, always use q1 = Integer.parseInt(input1.nextLine()); (Even better, use the BufferedReader class). That way, your reading will work smoothly.
Secondly, you can place the if (q1 == 4) within the if (yn1.equals("Y")) statement. If the user has typed "Y" then set correct = true; to proceed to the next question. Further, if the user's answer is correct then increment the counter of right answers else print wrong. So the loop looks like this:
while (correct == false) {
System.out.println("What is 2+2? ");
System.out.println("Choices: 0,2,4,8");
q1 = Integer.parseInt(input1.nextLine());
System.out.println("Are You Sure? (Y/N)");
yn1 = input1.nextLine();
if (yn1.equals("Y")) {
correct = true;
if (q1 == 4) {
System.out.println("You were correct 2+2 = 4");
count++;
} else
System.out.println("You were wrong");
}
}
A few things to look into:
You print "Choices: 0,2,4,8", but nothing stops the user to enter 3 or 3000. Is the choices statement necessary? Then you'll need to check if the user has entered within that range or not also.
Instead of copying & pasting this same loop n times, make use an an array. Have all questions & answers stored in some String array for now. Something like this:
for (int i = 0; i < questions.length; i++) {
boolean nextQ = false;
while (nextQ == false) {
System.out.println(questions[i]);
String ans = input1.nextLine();
System.out.println("Are You Sure? (Y/N)");
yn = input1.nextLine();
if (yn.equalsIgnoreCase("Y")) {
nextQ = true;
if (ans.equals(answers[i])) {
System.out.println("You were correct " + questions[i]
+ " = " + answers[i]);
count++;
} else
System.out.println("You were wrong");
}
}
}
I changed the boolean variable correct to nextQ to avoid confusion. Hope the sets you in the right direction.
I tried to compile your program.But I am getting some errors:-
error: variable q1 might not have been initialized
According to what I understand from ur question.Here is the program u want:-
import java.util.Scanner;
class stack1
{
public static void main (String[] args)
{
int q1=0 , q2 , q3, q4, q5, q6 , q7 ,q8 ,q9 ,q10 , a ;
boolean correct = false;
char yn1='Y';
Scanner input1 = new Scanner( System.in );
int count = 0 ;
while (correct == false)
{
System.out.println("What is 2+2? ");
System.out.println("Choices: 0,2,4,8");
q1 = input1.nextInt(); //used after loop
System.out.println("Are You Sure? (Y/N)");
char c = input1.next().charAt(0); // Changed LINE
if (c=='y') // Changed LINE
{
System.out.println("Exiting the program");
correct = true; //It should now stop the loop and carry on
break;
}
}
if ( q1 == 4) //q1 was stated during loop
System.out.println("You were correct 2+2 = 4");
else
System.out.println("You were wrong");
//Soon will add int score and add 1 each time its correct
// will be using 9 more loops the exact same way
}
}
I have mentioned all the changed lines with comment '//changed line' .
This is the answer for the edited Question:-
import java.util.Scanner;
class stack2
{
public static void main (String[] args)
{
int q1=0 , q2 , q3, q4, q5, q6 , q7 ,q8 ,q9 ,q10 , a ;
boolean correct = false;
char yn1='Y';
String s="";
System.out.println(s);
Scanner input1 = new Scanner( System.in );
int count = 0 ;
while (correct == false)
{
System.out.println("What is the capital city of Canada?");
System.out.println("Choices: Toronto, Montreal, Vancouver, Ottawa (capitals count)");
s = input1.nextLine();
System.out.println(s);
System.out.println("Are You Sure? (Y/N)");
char c = input1.next().charAt(0); // Changed LINE
if (c=='y') // Changed LINE
{
System.out.println("Exiting the program");
correct = true; //It should now stop the loop and carry on
break;
}
if (s.equals("Ottawa")) //q1 was stated during loop
System.out.println("You were correct, The capital is Ottawa");
else
System.out.println("You were wrong");
}
//Soon will add int score and add 1 each time its correct
// will be using 9 more loops the exact same way
}
}
Be careful while entering the input.It shoul be exactly "Ottawa". Best of luck
Related
Sorry I am new to this site so not sure how this will show up. I am trying to make a simple Rock, Paper, Scissors game. After the while statement, if R, P, S isn't entered, the program just does nothing. I want it to loop back to the question at the beginning so a right choice can be entered. Also, how would I enter a print statement like "Invalid Choice Please Retry"?
package rps.gameapp;
import java.util.Scanner;
public class RPSGameApp
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String userChoice;
String playAgain;
int randNum = (int) (Math.random() * 3);
do
{
System.out.println("Welcome to Rock, Paper, Scissors Game.");
System.out.println("Pick R, P, or S.");
userChoice = sc.nextLine();
while (!userChoice.equalsIgnoreCase("P")
&& !userChoice.equalsIgnoreCase("R")
&& !userChoice.equalsIgnoreCase("S"));
String compChoice = "";
switch (randNum)
{
case 0:
compChoice = "R";
break;
case 1:
compChoice = "P";
break;
case 2:
compChoice = "S";
break;
}
System.out.println("The computer entered \"" + compChoice + "\".");
if (compChoice.equalsIgnoreCase(userChoice))
{
System.out.println("Draw");
} else if (userChoice.equalsIgnoreCase(userChoice)
&& compChoice.equalsIgnoreCase("S")
|| userChoice.equalsIgnoreCase("P")
&& compChoice.equalsIgnoreCase("R")
|| userChoice.equalsIgnoreCase("S")
&& compChoice.equalsIgnoreCase("P"))
{
System.out.println("User Wins");
} else
{
System.out.println("User Loses");
}
System.out.print(
"Do you want to play again? (Y/N)");
playAgain = sc.nextLine();
} while (playAgain.equalsIgnoreCase("Y"));
System.out.println("Thanks for Playing!");
}
}
It looks like you forgot one do for your inner do while loop.
It should be :
do {
do {
System.out.println("Welcome to Rock, Paper, Scissors Game.");
System.out.println("Pick R, P, or S.");
userChoice = sc.nextLine();
} while (!userChoice.equalsIgnoreCase("P") && !userChoice.equalsIgnoreCase("R") && !userChoice.equalsIgnoreCase("S"));
...
} while (playAgain.equalsIgnoreCase("Y"));
Without that inner do (and the curly braces surrounding that loop's body), the inner loop becomes a while loop with an empty body.
Like Eran said, you need to wrap your do-while loop in another loop, that will keep asking user for correct input. This is fully working code. One thing that could be better is the message after user inputs wrong letter.
Edit: also make sure you draw random number for every iteration.
Edit 2: to change the message depending on user input you can introduce a new variable that will keep the track of number of times you asked user for correct input. If it is 0- it means user is asked the first time and we should print "Welcome" message. It is anything other than 0- you need to ask the user for correct input. After every round we assign zero to the variable again and the cycle repeats. I have implemented this change in the code. Note that this variable can also be a boolean.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String userChoice;
String playAgain;
int iterationNumber;
while (true) {
iterationNumber = 0;
do {
if (iterationNumber == 0) {
System.out.println("Welcome to Rock, Paper, Scissors Game.");
System.out.println("Pick R, P, or S.");
} else {
System.out.println("Please enter valid letter.");
System.out.println("Pick R, P, or S.");
}
iterationNumber++;
userChoice = sc.nextLine();
} while (!userChoice.equalsIgnoreCase("P")
&& !userChoice.equalsIgnoreCase("R")
&& !userChoice.equalsIgnoreCase("S"));
String compChoice = "";
int randNum = (int) (Math.random() * 3);
switch (randNum) {
case 0:
compChoice = "R";
break;
case 1:
compChoice = "P";
break;
case 2:
compChoice = "S";
break;
}
System.out.println("The computer entered \"" + compChoice + "\".");
if (compChoice.equalsIgnoreCase(userChoice)) {
System.out.println("Draw");
} else if (userChoice.equalsIgnoreCase("R")
&& compChoice.equalsIgnoreCase("S")
|| userChoice.equalsIgnoreCase("P")
&& compChoice.equalsIgnoreCase("R")
|| userChoice.equalsIgnoreCase("S")
&& compChoice.equalsIgnoreCase("P")) {
System.out.println("User Wins");
} else {
System.out.println("User Loses");
}
System.out.print(
"Do you want to play again? (Y/N)");
playAgain = sc.nextLine();
if (playAgain.equalsIgnoreCase("N")) {
break;
}
iterationNumber = 0;
}
System.out.println("Thanks for Playing!");
}
import java.util.*;
public class TestProject
{
public static void theMath()
{
double add = 1;
double subtract = 2;
double multiply = 3;
double divide = 4;
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
//Pick first number
System.out.println("Please enter a number: ");
int intOne = input.nextInt();
// Pick second number
System.out.println("Please enter another number: ");
int intTwo = input.nextInt();
//User chooses operator
System.out.println("Now please choose an operator (1 for add, 2 for subtract, 3 for mulitply, 4 for divide): ");
int userChoice = input.nextInt();
// Add
if (userChoice == add)
System.out.println("Your answer is: " + (intOne + intTwo));
// Subtract
else if (userChoice == subtract)
System.out.println("Your answer is: " + (intOne - intTwo));
// Multiply
else if (userChoice == multiply)
System.out.println("Your answer is: " + (intOne * intTwo));
// Divide
else if (userChoice == divide)
System.out.println("Your answer is: " + (intOne / intTwo));
// If wrong input
else
{
System.out.println("Nothing happens!");
System.out.println("Please make sure you entered a number and an operator.");
}
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
theMath();
System.out.println("Would you like to do another calculation?");
String redo = input.nextLine();
if(redo.equals("yes"))
theMath();
else if(redo.equals("no"))
System.out.println("Thanks for calculating with me! It certainly was fun!");
else
System.out.println("Please enter 'yes' or 'no' only.");
String yesNo = input.nextLine();
if(yesNo.equals("yes"))
theMath();
else
System.out.println("Thanks for calculating with me! It certainly was fun!");
}
}
I was wondering how I could recall the main method an infinite amount of times if I wanted to. What I was doing was just copying and pasting it over and over again but there has to be a better way. And also, I would like to know how to return a value has a decimal(so I could do 25/6 and get the correct answer).
Why not put only the statements that should be repeated inside a loop?
String redo;
do{
System.out.println("Would you like to do another calculation?");
redo = input.nextLine();
if(redo.equals("yes"))
theMath();
else if(redo.equals("no"))
System.out.println("Thanks for calculating with me! It certainly was fun!");
else
System.out.println("Please enter 'yes' or 'no' only.");
String yesNo = input.nextLine();
if(yesNo.equals("yes"))
theMath();
else
System.out.println("Thanks for calculating with me! It certainly was fun!");
}while(redo.equals("yes"))
As for the other part of your question. If you have two int values and want to get a decimal from a division, you can do it like this:
int x = 2;
int y = 3;
double result = (double)x/y;
System.out.println(result);
This is called casting.
This is the output of the program
I was able to do till to get this result by doing this program below
import java.util.Scanner;
public class aLittleQuiz {
public static void main(String[] args) {
// declaring varibles
String quizStart;
int quizAns1, quizAns2, quizAns3;
Scanner input = new Scanner(System.in);
System.out.println("Are you ready for a quiz? (y / n)");
quizStart = input.next();
System.out.println("Okay, here it comes!");
// quiz answer 1
System.out.println("\nWhat is the capital of Alaska? \n1) Melbourne\n2) Anchorage\n3) Juneau");
quizAns1 = input.nextInt();
if (quizAns1 == 3) {
System.out.println("That's right");
} else {
System.out.println("Your answer is wrong, sorry!");
}
// quiz answer 2
System.out.println("Q2) Can you store the value ''cat'' in a variable of type int? \n1) yes \n2) no");
quizAns2 = input.nextInt();
if (quizAns2 == 1) {
System.out.println("Sorry, ''cat'' is a string. ints can only store numbers.");
} else if (quizAns2 == 2) {
System.out.println("Correct!");
}
// quiz answer 3
System.out.println("What is the result of 9+6/3? \n1) 5\n2) 11 \n3) 15/3");
quizAns3 = input.nextInt();
if (quizAns3 == 2) {
System.out.println("That's correct!");
} else {
System.out.println("");
}
// if (quizAns == 3 && quizAns == ) {
// }
}
}
but how I can program this part?
"Overall, you got 2 out of 3 correct.
Thanks for playing!"
Declare a variable like int marks and increment it by one inside if\else block(which made for correct answer). And at the end print
System.out.println("Overall, you got" +marks+" out of 3 correct. Thanks for playing!");
Assuming your no of question is fixed( 3 )
String quizStart;
int quizAns1, quizAns2, quizAns3;
int marks=0;
Scanner input = new Scanner(System.in);
System.out.println("Are you ready for a quiz? (y / n)");
quizStart = input.next();
System.out.println("Okay, here it comes!");
// quiz answer 1
System.out.println("\nWhat is the capital of Alaska? \n1) Melbourne\n2) Anchorage\n3) Juneau");
quizAns1 = input.nextInt();
if (quizAns1 == 3) {
System.out.println("That's right");
++marks;
} else {
System.out.println("Your answer is wrong, sorry!");
}
// quiz answer 2
System.out.println("Q2) Can you store the value ''cat'' in a variable of type int? \n1) yes \n2) no");
quizAns2 = input.nextInt();
if (quizAns2 == 1) {
System.out.println("Sorry, ''cat'' is a string. ints can only store numbers.");
} else if (quizAns2 == 2) {
System.out.println("Correct!");
++marks;
}
// quiz answer 3
System.out.println("What is the result of 9+6/3? \n1) 5\n2) 11 \n3) 15/3");
quizAns3 = input.nextInt();
if (quizAns3 == 2) {
System.out.println("That's correct!");
++marks;
} else {
System.out.println("");
}
System.out.println("Overall, you got " +marks+" out of 3 correct. Thanks for playing!");
I was working on some assignments I had for my java class, and I came across this error:
public static final String ANSI_RED = "\u001B[31m";
public static final String ANSI_GREEN = "\u001B[32m";
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
System.out.println("Welcome to QuizApp! Programmed by Chris!");
System.out.println("Please type the number corrisponding to the correct answer.");
int score = 100;
for(int i = 0;i <5;i++) {
if (i == 0) {
System.out.println("What is the capital of America? ");
System.out.println("1) Washington D.C \t2) New York");
System.out.println("3) Philadelphia \t4) Manhatten");
int answer = myScanner.nextInt();
if (answer == 1) {
System.out.println(ANSI_GREEN+"Correct!");
}else{
System.out.println("Either your answer was wrong, or there was a syntax error.");
score = score - 20;
}
if (i == 1) {
System.out.println("What ocean do emporer penguins swim in? ");
System.out.println("1) The Indian Ocean \t2) The Pacific Ocean");
System.out.println("3) The Atlantic Ocean \t4) The Antarctic Ocean");
answer = myScanner.nextInt();
if (answer == 4); {
System.out.println(ANSI_GREEN+"Correct!");
}else{
System.out.println(ANSI_RED+"Either your answer was wrong, or there was a syntax error.");
}
}
}
}
}
}
It said I had an error with my curly brackets here:
if (i == 1) {
System.out.println("What ocean do emporer penguins swim in? ");
System.out.println("1) The Indian Ocean \t2) The Pacific Ocean");
System.out.println("3) The Atlantic Ocean \t4) The Antarctic Ocean");
answer = myScanner.nextInt();
if (answer == 4); {
System.out.println(ANSI_GREEN+"Correct!");
}else{
System.out.println(ANSI_RED+"Either your answer was wrong, or there was a syntax error.");
}
}
I was trying to put an if-else statement inside of an if statement. I know why its giving me this error, but I'm not sure how to fix it. (The error is most likely java thinking that the }else{ is paired with the first if statement.
The problem is here
if (answer == 4);
You have a semicolon after your if statement which terminates the condition. Remove it and you should be fine.
So I am trying to create a program for an assignment where the user would pick an animal, and depending on that animal (dog/chicken/fish), how many legs it has. If the user did not select one of the 3 animals, the game would then ask the user if they would like to play again. If the answer is y, then the program would start over, but if it is n, then the program would stop. The error is near the bottom where it states "String gameAnswer = input.nextLine();". It says that I have to rename gameAnswer. Could anyone help me fix this so that the program would work?
Thanks in advance!
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Choose an animal: ");
String text = input.nextLine();
char n;
char y;
char gameAnswer = 'n';
do
{
switch (text) {
case "dog":
System.out.println("How many legs does a dog have?");
int dg = input.nextInt();
if(dg == 4)
{
System.out.println("You win!");
}
else
{
System.out.println("You lose!");
}
break;
case "chicken":
System.out.println("How many legs does a chicken have?");
int chkn = input.nextInt();
if(chkn == 2)
{
System.out.println("You win!");
}
else
{
System.out.println("You lose!");
}
break;
case "fish":
System.out.println("How many legs does a fish have?");
int fsh = input.nextInt();
if(fsh == 0)
{
System.out.println("You win!");
}
else
{
System.out.println("You lose!");
}
break;
default:
break;
}
}
while(gameAnswer == 'y');
System.out.println("I don't know that animal. Do you want to try again? (y/n)");
String gameAnswer = input.nextLine();
}
The prompting and reading of the line should be within your loop
NOT
while(gameAnswer == 'y');
System.out.println("I don't know that animal. Do you want to try again? (y/n)");
char gameAnswer = input.nextLine();
BUT
System.out.println("I don't know that animal. Do you want to try again? (y/n)");
gameAnswer = input.nextLine();
while(gameAnswer == 'y');
ALSO
gameAnswer is already defined, so do not redefine it.
AND ALSO
You probably want gameAnswer = input.nextLine().charAt (0);
EDIT
also move
System.out.println("Choose an animal: ");
String text = input.nextLine();
to after
do