How do i add an play again option to this java code? - java

is there a way to declare a char early on but use it only later, because when i try to declare it as 0 early on then it will just cause an error because the answer of while is supposed to be 'Y'. i could get it to loop and play again by asking the question before playing but I only want it to ask the option to play again at the end of the game. would appreciate it if anyone could tell me how to get this to work, thank you.
public class soodsami_a3 {
public static void main(String[] args) {
Scanner sam = new Scanner(System.in);
// Random number generator
int Randomizer = (int)(Math.random() * 100) + 1;
while (playagain == 'y') {
System.out.println("I'm thinking of a number between 1 and 100");
System.out.println("What is it?");
System.out.print("Guess: ");
int Useranswer = sam.nextInt();
while (Useranswer != Randomizer) {
if (Useranswer < Randomizer) {
System.out.println("Too low.");
System.out.print("Guess: ");
Useranswer = sam.nextInt();
} else if (Useranswer > Randomizer) {
System.out.println("Too high.");
System.out.print("Guess: ");
Useranswer = sam.nextInt();
}
if (Useranswer == Randomizer) {
System.out.println("You got it!");
}
System.out.print("would you like to play again (Y/N) ");
char playagain = sam.next().toUpperCase().charAt(0);
}
}
System.out.println("Thanks for playing");
}
}

public static void main(String[] args) {
// ...
char playagain = 'y';
while (playagain == 'y') {
// ...
playagain = scan.next().toLowerCase().charAt(0);
}
System.out.println("Thanks for playing");
}

It would be a better practice to have playagain as a boolean and have it set to false on initialization. Then use a do-while cycle, to have the condition evaluated at the end of the cycle, so that it runs at least once
boolean playAgain = false;
do {
System.out.println("I'm thinking of a number between 1 and 100");
//..other code..
playAgain = sam.next().toUpperCase().charAt(0) == 'Y';
} while (playAgain);

Related

Guessing a number

I want to create a program that gives you three tries to find any given number. It's going to essentially be a guessing game. The problem is, I have to do this without any loops. So far, I'm only able to get input from the user, read that input and tell them if they've won or 'lost' the game. The program only runs once and stops(as expected).
I was told that it could be done without loops, albeit with a lot more code. Can you guys let me know what I'm doing wrong here and give me some pointers on what I should change? If you need clarification let me know.
Thanks.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner ran = new Scanner(System.in);
System.out.println("Enter a number: ");
int x = ran.nextInt();
if (x < 3) {
System.out.println("Too low. Try again.");
System.out.println("Enter a number: ");
} else if (x > 3) {
System.out.println("Too high. Try again");
} else if(x == 3) {
System.out.println("You win. Nice job.");
} else {
System.out.println("You lose");
}
System.out.println("Number Guessing Game (c) 2017 Anna Gibson");
}
}
You can do this using recursion. See this program. Find explanations within comments.
import java.util.Scanner;
public class HelloWorld {
private static Scanner ran = new Scanner(System.in);
//this is number of tries you want to give to user
private static int counter = 5;
//The actual number
private static final int NUM = 3;
public static boolean guessingMachine() {
//counter indicates that number of attempts remaining
if(counter == 0) {
return false;
}
counter--;
System.out.println("Enter a number: ");
int x = ran.nextInt();
if (x < NUM) {
System.out.println("Too low. Try again.");
//try again... call this method again
return guessingMachine();
} else if (x > NUM) {
System.out.println("Too high. Try again");
//try again... call this method again
return guessingMachine();
} else {
//x == NUM success
return true;
}
}
public static void main(String[] args) {
boolean result = guessingMachine();
if(result)
System.out.println("You win. Nice job.");
else
System.out.println("You lose");
System.out.println("Number Guessing Game (c) 2017 Anna Gibson");
}
}
You could next conditions:
get user input
if input is correct, congratulation user and exit
else
get user input //second attempt
if input is correct, congratulation user and exit
...
You can continue from there. The code you provided, where you tell the user if they are too high or low, would have to be included in each of the branches of the pseudocode above.
I think the main purpose of this exercise is intended for you to strengthen your nested if-else concepts.
import java.util.Scanner;
public class HelloWorld{
public static void main(String []args){
int num=3;
int count=1;
Scanner ran = new Scanner(System.in);
System.out.println("Enter a number: ");
int x = ran.nextInt();
if(x>num || x<num)
{
System.out.println("incorrect guess");
count++;
System.out.println("Enter a number: ");
x = ran.nextInt();
if(x>num || x<num)
{
System.out.println("incorrect guess");
count++;
System.out.println("Enter a number: ");
x = ran.nextInt();
if(x>num || x<num)
{
System.out.println("incorrect guess YOU LOSE");
}
else
{
System.out.println("YOU WIN");
}
}
else
{
System.out.println("YOU WIN");
}
}
if(x==num && count==1)
{
System.out.println("YOU WIN");
}
System.out.println("Number Guessing Game (c) 2017 Anna Gibson");
}
}

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 go back into a while-loop, from an if statement?

Here's what i've been working on. I'm trying loop this while method, using booleans. (My teacher is incompetent, so i've been learning out of textbook.)
else { System.out.println("Do you want to restart? Y/N");
string answer = scn.next();
return;
if (scn.hasNext() && !no)) {
System.out.println("end");
} else{
continue;
}
/*if (repeat) {
continue;
} else {
System.out.println("End");
break;
}*/
}
This is nested in a while loop like so ....
import java.util.Scanner; import java.lang.String;
public class booleanvariables {
public static void main (String[] args){
Scanner scn = new Scanner(System.in);
int score1, score2;
String answer, e;
boolean bothHigh, atLeastOneHigh, atLeastOneModerate, noLow, tooLow, repeat;
while (true) {
System.out.print("Enter the first test score:\t");
score1 = scn.nextInt();
System.out.print("Enter the second test score:\t");
score2 = scn.nextInt();
answer = null;
e = "n";
bothHigh = (score1 >= 90 && score2 >= 90);
atLeastOneHigh = (score1 >= 90 || score2 >= 90);
atLeastOneModerate = (score1 >= 70 || score2 >= 70);
noLow = !(score1 < 50 || score2 < 50);
tooLow = (score1 <= 50 || score2 <= 50);
repeat = (answer == "yes" || answer == "y"); //|| answer == Y || answer == Yes);
if (tooLow)
System.out.println("Inputs are too low");
if (bothHigh)
System.out.println("Qualified to be a manager");
if (atLeastOneHigh)
System.out.println("Qualified to be a supervisor");
if (atLeastOneModerate && noLow)
System.out.println("Qualified to be a clerk");
/** NESTED WRONG I'M AWARE
*/
else { System.out.println("Do you want to restart? Y/N");
string answer = scn.next();
return;
if (scn.hasNext() && !no)) {
System.out.println("end");
} else{
continue;
}
/*if (repeat) {
continue;
} else {
System.out.println("End");
break;
}*/
}
}
}
}
This is much simpler than you think.
Just do it like this:
boolean stop = false;
while(!stop) {
//do whatever you want here
System.out.println("Do you want to quit?(yes or no");
String input = scan.nextLine();
if(input.equals("no")) {
stop = true;
}
}
That way, if you enter "no", it'll set the boolean to true, which then will make the condition for the while loop, !stop, equal to false.
answer == "yes"
You are checking if two objects are the same. You should use the equals method answer.equals("yes") || answer.equals("y")
Tested and Working to My Liking
I've reworked some branching. ( I use BlueJ as a compiler and it thinks this is an error without the input = scn.nextLine();
do {
//same booleans i've been using
if (!stop) {
System.out.print("Do you want to quit? (yes or no):\t");
//String input;
input = scn.nextLine();
}
//String input;
input = scn.next();
if(input.equals("yes")) {
stop = true;
System.out.println("Goodbye");
return;
}
} while (!stop);
I really don't know why blue J doesn't like it when initialize input from within the if statement

How to use while loop

Ask the user to guess a number until the guess is equal random number. press 0 to quit and ask the user if they want to play again.
My problem, 0 for quit is, not working. How can I make it work with while loop?
thanks
import java.util.Random;
import java.util.Scanner;
public class Guessing
{
public static void main(String[]args){
String playAgain = "y";
final int MAX =100;
int randomNumber;
int numberofGuess = 0;
int guess ;
boolean flag=false;
Scanner input = new Scanner(System.in);
Random rand = new Random();
Scanner inputYes= new Scanner(System.in);
while(playAgain.equalsIgnoreCase("y"))//do
{
System.out.println("Guess a number between 1 and "+ MAX );
randomNumber = rand.nextInt(MAX) +1;
numberofGuess = 0;
System.out.println( "enter a guess(0 to quit):");
guess= input.nextInt();
numberofGuess++;
if(guess >0)
if (guess == randomNumber)
{
System.out.println("you guessed corect.");
System.out.println("you guessed " +numberofGuess+ " times");
}
else if(guess < randomNumber)
System.out.println("you guess is too low.");
else if(guess > randomNumber)
System.out.println("you guess is too high.");
System.out.println("Do you want to play again? (y/n)");
playAgain = inputYes.nextLine();
}//while(playAgain.equalsIgnoreCase("y"));
}
}
Your loop runs until the expression in parantheses is false:
while (true) {
// this will be executed forever
}
while (false) {
// this will never be executed
}
a = 0;
while (a == 0) {
a = 1;
// this will be executed exactly once, because a is not equal 0 on the second run
}
guess = 1
while (guess != 0) {
// this will executed until the user enters "0"
readln(guess);
}
Please keep in mind that this is pseudo code. It will not compile.

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