Wrong Quiz result - java

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!");

Related

How do I fix my loops from taking the enter key as input.in Java?

This question is similar to a question I had previously about loops taking my enter key as input. For my class, I need to write a program that is a number-guessing game that whenever the user enters correctly, the loop ends. But I run into the problem as the enter key being taken as input. How can I stop this from occurring? Here is my code I have so far.
String secretNumber = "6";
String guess = "";
while(!guess.equals(secretNumber)) {
System.out.println("Guess a number between 1 and 10");
guess = scan.next();
if(guess == "6") {
System.out.println("You Win!");
}
else if(guess == "5") {
System.out.println("Try again!");
}
else if(guess == "4") {
System.out.println("Try again!");
}
else if(guess == "3") {
System.out.println("Try again!");
}
else if(guess == "2") {
System.out.println("Try again!");
}
else if(guess == "1") {
System.out.println("Try again!");
}
else if(guess == "7") {
System.out.println("Try again!");
}
else if(guess == "8") {
System.out.println("Try again!");
}
else if(guess == "9") {
System.out.println("Try again!");
}
else if(guess == "10") {
System.out.println("Try again!");
}
else {
System.out.println("You did not enter a number between 1 and 10");
}
}
}
}
If you use == operator it doesn't compare the value of the string. So to check if a string's value equals to another, you must use string.equals(anotherString) method. In your case your code should be like :
String secretNumber = "6";
String guess = "";
while(!guess.equals(secretNumber)) {
System.out.println("Guess a number between 1 and 10");
guess = scan.next();
if(guess.equals("6")) {
System.out.println("You Win!");
}
else if(guess.equals("5")) {
System.out.println("Try again!");
}
..........
Also to refactor the code this version is more readable and simpler.
String secretNumber = "6";
String guess = guess = scan.next();
System.out.println("Guess a number between 1 and 10");
while(!guess.equals(secretNumber)) {
if(guess.equals(secretNumber)) {
System.out.println("You Win!");
break;
}
else{
System.out.println("Try again!");
}
First Strings are compared by equals second you need to learn how to reduce your code because while(!guess.equals(secretNumber)) will continue until 6 is entered so it will print anything inside it you we just print Try Again
public class GuessIt{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String secretNumber = "6";
String guess = "";
System.out.println("Guess a number between 1 and 10");
guess = scan.next();
while(!guess.equals(secretNumber)) {
System.out.println("Try again");
System.out.println("Guess a number between 1 and 10");
guess = scan.next();
}
System.out.println("You guessed it");
}
}
While your code is not the best way to implement a guessing game, I will play along if it helps you.
I don't entirely know what you mean by the enter key being taken as input. Are you typing a value into the terminal before you press enter?
String secretNum = 6;
String guess = "";
System.out.println("Guess a number between 1 and 10");
while(!guess.equals(secretNum)) {
guess = scan.next();
if(Integer.parseInt(guess)>10 || Integer.parseInt(guess)<1) {
System.out.println("Re-enter a number between one and ten");
}
}
System.out.println("You guessed it!");

Q : Not understanding loop process? or possible if statements?

I am working on a project that involves creating a rental car calculator.
What I am trying to do is make it to where when asked: "What vehicle would you like to rent??". If a number that is not between 1-3 is entered when the user is prompted this, then I want the program to loop back to the point of being asked vehicle type again.
Similarly, when prompted for 'Please enter the number of days rented. (Example; 3) : ' I want to only allow the user to input whole positive numbers. for instance, not allowing input of 3.1, 2.35, 0.35 -2 and, etc...
here is what I have written and my attempt at these questions :
package inter;
import java.util.Scanner;
public class Inter {
public static void main(String []args){
int count=0;
int days;
double DailyFee=0, NontaxTotal, CarType, Total,FullTotal=0;
Scanner in=new Scanner(System.in);
System.out.println("If there are any customer press 1 else press 0");
int cus=in.nextInt();
while(cus!=0){
count++;
System.out.print("What vehical would you like to rent?\n");
System.out.println("Enter 1 for an economy car\n");
System.out.println("Enter 2 for a sedan car\n");
System.out.println("Enter 3 for an SUV");
CarType = in.nextInt();
if (CarType == 1) {
DailyFee=31.76;
}
else if(CarType == 2) {
DailyFee=40.32;
}
else if(CarType == 3) {
DailyFee=47.56;
}
else if(CarType <= 0) {
System.out.println("input is not a positive Integer ");
System.out.println("Please enter a positive integer value: ");
cus = 0; }
else if(CarType > 4) {
System.out.println("input is not a positive Integer ");
System.out.println("Please enter a positive integer value: ");
cus = 0; }
System.out.print("Please enter the number of days rented. (Example; 3) : ");
days = Integer.valueOf(in.nextLine());
double x=days;
NontaxTotal = (DailyFee * x);
Total = (NontaxTotal * 1.06);
FullTotal+=Total;
System.out.printf("The total amount due is $ %.2f \n",Total);
System.out.println("If there are any customer press 1 else press 0");
cus=in.nextInt();
}
System.out.println("Count of customers : "+count);
System.out.printf("Total of the Day : $ %.2f",FullTotal);
}
}
Let me help you with this,
I made this code for you, i tried it and it worked
this will check if both answers were whole numbers (integers) and more than zero and will also check if the answer was numeric in the first place so that if the user answered with letters he will be prompted to try again
This is my suggestion:
basically i used the try-catch block with InputMismatchException to detect if the answer was not an integer (whole number ) or was not numeric at all, every time a mistake is detected i flip a boolean to false and keep looping as long as this boolean is false (i flip the boolean back to true before checking otherwise once the user gives a wrong answer he will always be prompted to answer even if he gave a correct answer after)
int vehicleType;
int numberOfDays;
double dailyFee;
boolean validAnswer1 = false;
boolean validAnswer2 = false;
Scanner scan = new Scanner(System.in);
while (validAnswer1 == false) {
validAnswer1 = true;
System.out.println("Choose Vehicle Type");
try {
vehicleType = scan.nextInt();
if (vehicleType <= 0) {
System.out.println("Number must be more than zero");
validAnswer1 = false;
} else if (vehicleType >= 4) {
System.out.println("Number should be from 1 to 3");
validAnswer1 = false;
} else {
if (vehicleType == 1) {
dailyFee=31.76;
} else if(vehicleType == 2) {
dailyFee=40.32;
}else if(vehicleType == 3) {
dailyFee=47.56;
}
while (validAnswer2 == false) {
validAnswer2 = true;
try {
System.out.println("Enter number of days rented ?");
numberOfDays = scan.nextInt();
if (numberOfDays <= 0) {
System.out.println("Number of days must be more than zero");
validAnswer2 = false;
} else {
// calculate your rent total here
}
} catch(InputMismatchException ex) {
System.out.println("Answer must be an Integer");
validAnswer2 = false;
scan.next();
}
}
}
} catch (InputMismatchException ex) {
validAnswer1 = false;
System.out.println("Answer must be an Integer");
scan.next();
}
}
Hope this was useful, do let me know if you still need help

How to make code loop with boolean specified at the end of code?

Try to make my code so that I can ask the user if they want to play again, however I'm confused how I'm supposed to go about this.
Scanner in = new Scanner(System.in);
int randomNum = 1 + (int)(Math.random() * 100);
System.out.println(randomNum);
Boolean playAgain = true;
while (playAgain) {
System.out.print("I'm thinking of a number between 1 and 100.\nWhat is it?\nGuess: ");
int guessNum = in.nextInt();
while ((guessNum > randomNum) || (guessNum < randomNum)) {
if (guessNum > randomNum) {
System.out.print("Too High.\nGuess: ");
guessNum = in.nextInt();
} else if (guessNum < randomNum) {
System.out.print("Too Low.\nGuess: ");
guessNum = in.nextInt();
}
}
System.out.println("You got it!\nPlay again? (Y/N) ");
String answer = in.next();
if (answer == "y") {
playAgain = true;
} else {
playAgain = false;
System.out.println("Thanks for playing!");
}
}
You have used == equals Relational Operator which usually used to check string reference not the value actually. So, even if answer contains y then your conditional expression never returns true as a Result.
For Reference : Visit Here For More Info ( '==' vs 'equals()' method)
String answer = in.next();
//problem with this line becuase == operator use to check reference instead of value
if (answer == "y") {
playAgain = true;
} else {
playAgain = false;
System.out.println("Thanks for playing!");
}
So change your code as like below
String answer = in.next();
if (answer.startsWith("y") || answer.startsWith("Y")) { // Now this willl work fine to your code
playAgain = true;
} else {
playAgain = false;
System.out.println("Thanks for playing!");
}
It May help You
do {
System.out.print("I'm thinking of a number between 1 and 100.\nWhat is it?\nGuess: ");
int randomNum = 1 + (int) (Math.random() * 100);
System.out.println(randomNum);
int guessNum = in.nextInt();
do {
if (guessNum > randomNum) {
System.out.print("Too High.\nGuess: ");
guessNum = in.nextInt();
} else if (guessNum < randomNum) {
System.out.print("Too Low.\nGuess: ");
guessNum = in.nextInt();
}
}while ((guessNum > randomNum) || (guessNum < randomNum));
System.out.println("You got it!\nPlay again? (Y/N) ");
answer = in.next();
}while(answer.equals("y"));
If you want to use playAgain var, then use
answer.equals("y")
to compare two strings instead of ==.
otherwise have your full code inside while block or do while. And if user wants to play, then do continue, otherwise do break;
while(true)
{
// your code
String answer = in.next();
if (answer == "y") {
continue;
} else {
System.out.println("Thanks for playing!");
break;
}
}

How to call a statement over and over again in Java

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.

Restart simple java game

Here is a simple java number guessing game.
After the game has finished I would like to ask the user whether he wants to play again like: Do you want to play again? (Answer with Y/N) If the user inputs Y the game will restart and random a new number, if he reply with 'N ' the game will end. Here's my code :
import static java.lang.Math.*;
import java.util.Scanner;
public class HomeWorkLoopGame1 {
public static void main(String[] args) {
System.out.print("Welcome to number guessing game !\n");
System.out.println("Guess a number range from 1 to 100, You have 5 guess to win this game");
int answer = (int) (random()*100);
Scanner guess1 = new Scanner (System.in);
System.out.println("To begin please input your number");
int num1 = guess1.nextInt();
if (num1<answer) {
System.out.print(num1);
System.out.print(" Your answer is too small\n");
System.out.println("Try again! Please input your second guess");
}
else if (num1>answer){
System.out.println(num1);
System.out.print("Your answer is too big\n");
System.out.println("Try again! Please input your second guess");
}
else {
System.out.println("Congratulation! Your answer is correct! You win !");
}
int num2 = guess1.nextInt();
if (num2<answer) {
System.out.print(num2);
System.out.print(" Your answer is too small\n");
System.out.println("Try again! Please input your third guess");
}
else if (num2>answer){
System.out.println(num2);
System.out.print("Your answer is too big\n");
System.out.println("Try again! Please input your third guess");
}
else {
System.out.println("Congratulation! Your answer is correct! You win !");
}
int num3 = guess1.nextInt();
if (num3<answer) {
System.out.print(num3);
System.out.print(" Your answer is too small\n");
System.out.println("Try again! Please input your fourth guess");
}
else if (num3>answer){
System.out.println(num3);
System.out.print("Your answer is too big\n");
System.out.println("Try again! Please input your fourth guess");
}
else {
System.out.println("Congratulation! Your answer is correct! You win !");
}
int num4 = guess1.nextInt();
if (num4<answer) {
System.out.print(num4);
System.out.print(" Your answer is too small\n");
System.out.println("Try again! Please input your final guess");
}
else if (num4>answer){
System.out.println(num4);
System.out.print("Your answer is too big\n");
System.out.println("Try again! Please input your final guess");
}
else {
System.out.println("Congratulation! Your answer is correct! You win !");
}
int num5= guess1.nextInt();
if (num5<answer) {
System.out.print(num5);
System.out.print(" Your answer is too small\n");
System.out.println("Game Over");
}
else if (num5>answer){
System.out.println(num5);
System.out.print("Your answer is too big\n");
System.out.println("Game Over");
}
else {
System.out.println("Congratulation! Your answer is correct! You win !");
}
System.out.println("Correct Answer is "+ answer);
Scanner userReply = new Scanner (System.in);
char reply;
System.out.println("Do you want to play again? Answer with Y/N)");
}
}
You can try something like this. By the way this is not a good way to do this.
Scanner userReply = new Scanner(System.in);
System.out.println("Do you want to play again? Answer with Y/N)");
String answer= userReply.nextLine().toLowerCase();
if("y".equals(answer)){
main(args); // recursively call
}else {
System.out.println("game exit");
}
You can use do-while to do it in proper way.
Better way
public static void main(String[] args) {
boolean isValid;
do {
isValid = true;
runGame();
Scanner userReply = new Scanner(System.in);
System.out.println("Do you want to play again? Answer with (Y/N)");
String answer = userReply.nextLine().toLowerCase();
if ("y".equals(answer)) {
isValid =true;
} else {
isValid =false;
System.out.println("game exit");
}
} while (isValid);
}
public static void runGame() {
// your game logic
}
It is better (I think) to make a method for the play function.
public static void main(String[] args) {
playGame ();
System.out.print("Enter something:");
String input = System.console().readLine();
if (input=="y"){
playGame();
} else {
System.exit(0);
}
}
private void playGame() {
System.out.print("Welcome to number guessing game !\n");
System.out.println("Guess a number range from 1 to 100, You have 5 guess to win this game");
int answer = (int) (random()*100);
Scanner guess1 = new Scanner (System.in);
....
System.out.println("Correct Answer is "+ answer);
Scanner userReply = new Scanner (System.in);
char reply;
System.out.println("Do you want to play again? Answer with Y/N)");
}
You can call the main method for the class and create an instance of the class as so:
HomeWorkLoopGame1 variable = new HomeWorkLoopGame1();
HomeWorkLoopGame1.main(args);
Basically, it runs the game again from scratch - as if the player were starting to play the game again for the first time.
It would be something like this:
Scannner in = new Scanner(System.in);
System.out.println("Do you want to play again? Answer with Y/N");
String answer = in.nextLine().toLowerCase();
if(answer.equals.("Y")){
HomeWorkLoopGame1 variable = new HomeWorkLoopGame1();
HomeWorkLoopGame1.main(args);
}
else{
//exit
}
However I haven't tested this so I'm not 100% sure it might work. Best of luck
Edit:
- Wrap the code in a for loop to repeat it numerous times rather than just once
Just put a do-while loop inside your main method.
As the first line put:
do {
Immediately after System.out.println("Do you want to play again? Answer with Y/N)"); put:
while (reply=='Y' or reply=='y');
You'll need to make sure you're reading in the reply properly etc of course.
You could do the whole thing in a loop:
public static void main(String[] args) {
while (true) {
// your code goes here
System.out.println("Do you want to play again? Answer with Y/N)");
try {
char reply;
reply = (char) System.in.read(); // read a char
if (Character.toLowerCase(reply) != 'y') // when equals to Y break the loop
break;
} catch (Exception e) {
e.printStackTrace();
}
}
}
I tried not to change too much of your original code. I added a few while loops, some comments and additional code to handle the user's response. I hope it helps.
import static java.lang.Math.*;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
boolean play = true;
boolean notCorrect = true;
while (play) {
while (notCorrect) {
System.out.print("Welcome to number guessing game !\n");
System.out.println("Guess a number range from 1 to 100, You have 5 guess to win this game");
int answer = (int) (random() * 100);
Scanner guess1 = new Scanner(System.in);
//Guess 1
System.out.println("To begin please input your number");
int num1 = guess1.nextInt();
if (num1 < answer) {
System.out.print(num1);
System.out.print(" Your answer is too small\n");
System.out.println("Try again! Please input your second guess");
} else if (num1 > answer) {
System.out.println(num1);
System.out.print("Your answer is too big\n");
System.out.println("Try again! Please input your second guess");
} else {
System.out.println("Congratulation! Your answer is correct! You win !");
break;
}
//Guess 2
int num2 = guess1.nextInt();
if (num2 < answer) {
System.out.print(num2);
System.out.print(" Your answer is too small\n");
System.out.println("Try again! Please input your third guess");
} else if (num2 > answer) {
System.out.println(num2);
System.out.print("Your answer is too big\n");
System.out.println("Try again! Please input your third guess");
} else {
System.out.println("Congratulation! Your answer is correct! You win !");
break;
}
//Guess 3
int num3 = guess1.nextInt();
if (num3 < answer) {
System.out.print(num3);
System.out.print(" Your answer is too small\n");
System.out.println("Try again! Please input your fourth guess");
} else if (num3 > answer) {
System.out.println(num3);
System.out.print("Your answer is too big\n");
System.out.println("Try again! Please input your fourth guess");
} else {
System.out.println("Congratulation! Your answer is correct! You win !");
break;
}
//Guess 4
int num4 = guess1.nextInt();
if (num4 < answer) {
System.out.print(num4);
System.out.print(" Your answer is too small\n");
System.out.println("Try again! Please input your final guess");
} else if (num4 > answer) {
System.out.println(num4);
System.out.print("Your answer is too big\n");
System.out.println("Try again! Please input your final guess");
} else {
System.out.println("Congratulation! Your answer is correct! You win !");
break;
}
//Guess 5
int num5 = guess1.nextInt();
if (num5 < answer) {
System.out.print(num5);
System.out.print(" Your answer is too small\n");
System.out.println("Game Over");
} else if (num5 > answer) {
System.out.println(num5);
System.out.print("Your answer is too big\n");
System.out.println("Game Over");
} else {
System.out.println("Congratulation! Your answer is correct! You win !");
break;
}
System.out.println("Correct Answer is " + answer);
break;
} // while(correct)
Scanner userReply = new Scanner(System.in);
String reply;
System.out.println("Do you want to play again? Answer with (Y/N)");
reply = userReply.next().toLowerCase();
if (reply.equals("y")) {
play = true;
} else if (reply.equals("n")) {
play = false;
} else {
System.out.println("Invalid choice.");
break;
}
} // while(play)
} // main()
} // class Test

Categories