1 year ago
#380170
Johanna
i need to output the final part of my JAVA program which is just a game over string , how can i insert it?
these is my program i need to output "game over" if the user enter the string no instead of yes, right now it only works with the yes but i dont know how to add the other option the game is suppose to ask the user for a seed , then for a number from 1 to 100 and then the user has to guees the number, once the user guesses the number it asks if it wants to play again, with option of yes or no, i have the yes but i dont know how to output the no.
import java.util.Random;
import java.util.Scanner;
public class GuessANumber_part2 {
public static void main(String[] args) {
//Method generates a random number and per user's
//input it prints if is to low, to high or the
//correct number
guessNumber();
}
public static void guessNumber() {
//Generating a seed number
System.out.println("Enter a seed:\n");
Scanner scanner = new Scanner(System.in);
int seed = scanner.nextInt();
//variable counts number of guesses
int guess;//variable holds user's guess
boolean play = true;//variable to run while
//Generating random object
Random random = new Random(seed);
int correctNum = random.nextInt(100) + 1;
//Outer loop count the amount of guesses
//Prompts user to play the game again
while(play) {
//welcome statement, getting the initial input
System.out.println("Welcome!\n"
+ "Please enter a number between 1 and 100:");
//variables
guess = scanner.nextInt();//saves the initial input
int count = 1;//count the number of guesses
//Inner loop outputs if the number given by the user
//is either to high, to low or if is the correct number
while( guess != correctNum) {
if(guess < correctNum) {
System.out.println("Too low. Guess again:");
}else if(guess > correctNum) {
System.out.println("Too high. Guess again:");
}
count++;// keeps count of N of guesses
//welcome message and input statement
System.out.println("Welcome!\n"
+ "Please enter a number between 1 and 100:");
guess = scanner.nextInt();
}
//outer loop statement,Prompts the user to run or
//not run game again
System.out.println("Congratulations. You guessed correctly!\n"
+ "You needed " + count + " guesses.\n");
System.out.println("Do you want to play again? Answer \"yes\""
+ " or \"no\":");
//Output statement sets play to answer "yes"
play = scanner.next().toLowerCase().equals("yes");
}
}
}
java
if-statement
boolean
logic
0 Answers
Your Answer