How to make 'end game' method in java - java

so i made a game, in which user needs to guess the random number or letter. I want to make it so that when the user writes 'end game' during the game (when he guesses the number), he is being redirected to the menu (using the main(args); method). In fact, String value cannot be writen in int input. So when i write 'end game' during the game cycle, it just crashes. What should i do?
Heres code of my game:
import java.util.Scanner;
public class TwoGames {
public static void main(String[] args) { // main menu
Scanner scan = new Scanner(System.in);
System.out.println("Choose the game\n Type 'letter' or 'number' to choose the game");
String UserAnswer = "";
UserAnswer = scan.next();
if (UserAnswer.equalsIgnoreCase("number")) {
number(args);
}else if(UserAnswer.equalsIgnoreCase("letter")){
letter(args);
}
scan.close();
}
public static void letter (String[] args) {
Scanner scan = new Scanner(System.in);
String playAgain = "";
String ReTurn = "";
String Stop = "";
int numberOfTries = 0;
do {
System.out.println("Guess the Letter");
char randomLetter = (char) (Math.random() * 26 + 65);
char enteredLetter = 0;
while(true){
enteredLetter = Character.toUpperCase(scan.next().charAt(0));
numberOfTries = numberOfTries + 1;
if(enteredLetter==randomLetter)
{
System.out.println("Correct Guess");
System.out.println("The letter is:"+randomLetter);
System.out.println("It only took you " + numberOfTries + " tries! Good work!");
break;
}
else if(enteredLetter>randomLetter)
{
System.out.println("Incorrect Guess");
System.out.println("The letter entered is too high");
}
else if(enteredLetter<randomLetter)
{
System.out.println("Incorrect Guess");
System.out.println("The letter entered is too low");
}
}
System.out.println("Would you like to play again (y/n)?");
playAgain = scan.next();
} while (playAgain.equalsIgnoreCase("y"));
System.out.println("Thank you for playing! Goodbye! \n Type 'return' to return to main menu");
ReTurn = scan.next();
if (ReTurn.equalsIgnoreCase("return"))
main(args);
scan.close();
}
public static void number(String[] args) { //heres the number guessing game
Scanner scan = new Scanner(System.in);
String playAgain = "";
String ReTurn = "";
String Stop = "";//variable to stop game
do {
int theNumber = (int)(Math.random() * 100 + 1);
int numberOfTries = 0;
do {
int guess = 0;
while (guess != theNumber) {
System.out.println("Guess a number between 1 and 100:");
guess = scan.nextInt();
numberOfTries = numberOfTries + 1;
if (guess < theNumber)
System.out.println(guess + " is too low. Try again.");
else if (guess > theNumber)
System.out.println(guess + " is too high. Try again.");
else {
System.out.println(guess + " is correct. You win!");
System.out.println("It only took you " + numberOfTries + " tries! Good work!");
}
}
} while (Stop.equalsIgnoreCase("end game"));
main(args);// this sends user to main menu
System.out.println("Would you like to play again (y/n)?");
playAgain = scan.next();
} while (playAgain.equalsIgnoreCase("y"));
System.out.println("Thank you for playing! Goodbye! \n Type 'return' to return to main menu");
ReTurn = scan.next();
if (ReTurn.equalsIgnoreCase("return"))
main(args);
scan.close();
}
}
I am novice programmer, so yeah, thats might be a dumb question, because im learning. Anyway, any help and explanation would be useful.

To solve this problem, you should input a string, check if it equals to "End game" message and if not continue your code.
For example, replace this line:
guess = scan.nextInt();
In this code:
String input = scan.next();
if(input.equals("End game")){
main(args);
return;
}
guess = Integer.parseInt(input);
That code get a String input called input, check if he equals to "End game" and if not continue your guess loop.

Related

I'm having trouble outputing the user's amount of guesses in a Hangman game

This is basically just a hangman project for my class and I'm not allowed to use arrays. The word is hidden with dashes to the user.The user has to pick a letter and the number of spaces they would like to check. The user has a certain amount of guess depending on the difficulty they choose. If the letter they guessed is in at least one of the spaces they chose then the user loses no guesses, if the letter they guessed is in none of the spaces they chose then the user loses a guess.
for example the output should look like
The secret word is: loops
The word is: -----
Please enter the letter you want to guess
k
Please enter the spaces you want to check (separated by spaces)
0 1 2 3
Your letter was not found in spaces you provided
Guesses Remaining: 14
But it currently looks like this
The secret word is: loops
The word is: -----
Please enter the letter you want to guess
k
Please enter the spaces you want to check (separated by spaces)
0 1 2 3
Your letter was not found in spaces you provided
Guesses Remaining: 14
Your letter was not found in spaces you provided
Guesses Remaining: 13
Your letter was not found in spaces you provided
Guesses Remaining: 12
Your letter was not found in spaces you provided
Guesses Remaining: 11
Here is what I have so far
package e;
import java.util.Scanner;
public class HangmanBeta{
private static final boolean testingMode = true;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
keyboard.useDelimiter("\\n");
while (true) {
System.out.println("Enter your difficulty: Easy (e), Intermediate (i), or Hard (h)");
String diff = keyboard.next();
int amountOfSpaces = 0;
String response = "";
String guess = "";
String newGuess = "";
String letterInput = "";
int count = 0;
String newWord = "loops";//RandomWord.newWord();
int guesses = 0;
for (int i = 0; i < newWord.length(); i++) {
guess = newWord.replaceAll("[^#]", "-");
}
if ((diff.equalsIgnoreCase("e")) || (diff.equalsIgnoreCase("i")) || (diff.equalsIgnoreCase("h"))) {
if (diff.equalsIgnoreCase("e"))
{
guesses = 15;
}
if(diff.equalsIgnoreCase("i"))
{
guesses = 12;
}
if(diff.equalsIgnoreCase("h"))
{
guesses = 15;
}
if (testingMode == true)
{
System.out.println("The secret word is:" + " " + newWord);
}
System.out.println("The word is:" + " " + guess);
while(!newWord.equalsIgnoreCase(guess))
innerloop:
{ while(true)
{
System.out.println("Please enter the letter you want to guess");
letterInput = keyboard.next();
letterInput = Character.toString(letterInput.charAt(0));
if(!Character.isLetter(letterInput.charAt(0)))
{
System.out.println("Your input is not valid, try again");
break;
}
if(letterInput.equalsIgnoreCase("solve"))
{
System.out.println("Please solve the answer:");
String userSolve = keyboard.next();
if (!userSolve.equalsIgnoreCase(newWord))
{
System.out.println("That is not the secret word");
guesses = guesses - 1;
System.out.println("Guesses remaining: " + guesses);
}
else
{
System.out.println("You win!");
System.out.println("You have guessed the word! Congratulations");
System.out.println("Would you like to play again? Yes(y) or No (n)");
response = keyboard.next();
if (response.equalsIgnoreCase("n"))
{
System.exit(0);
}
if(response.equalsIgnoreCase("y"))
{
continue;
}
}
}
System.out.println("Please enter the spaces you want to check (separated by spaces)");
String spaces = keyboard.next();
amountOfSpaces = spaces.length();
if (diff.equalsIgnoreCase("e"))
{
if(amountOfSpaces != 7)
{
System.out.println("Your input is not valid, try again");
break innerloop;
}
}
if (diff.equalsIgnoreCase("i"))
{
if(amountOfSpaces != 5)
{
System.out.println("Your input is not valid, try again");
break innerloop;
}
}
if (diff.equalsIgnoreCase("h"))
{
if(amountOfSpaces != 3)
{
System.out.println("Your input is not valid, try again");
break innerloop;
}
}
for ( String a : spaces.split("\\s"))
{
int x = Integer.valueOf(a);
if (x > guess.length())
{
System.out.println("Your input is not valid, try again");
break innerloop;
}
if (Character.toLowerCase(newWord.charAt(x)) == letterInput.charAt(0))
{
//System.out.println("Guess is correct for position " + x);
guess = guess.substring(0, x) + letterInput + guess.substring(x + 1, guess.length());
}
if (Character.toLowerCase(newWord.charAt(x)) != letterInput.charAt(0))
{
guesses= guesses - 1;
System.out.println("Your letter was not found in spaces you provided");
System.out.println("Guesses Remaining: " + guesses);
}
if (guesses == 0)
{
System.out.println("You have failed to guess the word....:(");
System.out.print("Would you like to play again? Yes(y) or No(n)");
response = keyboard.next();
if (response.equalsIgnoreCase("n"))
{
System.exit(0);
}
if(response.equalsIgnoreCase("y"))
{
continue;
}
}
}
}
if (newWord.equalsIgnoreCase(guess))
{
System.out.println("You win!");
System.out.println("You have guessed the word! Congratulations");
System.out.println("Would you like to play again? Yes(y) or No (n)");
response = keyboard.next();
if (response.equalsIgnoreCase("n"))
{
System.exit(0);
}
if (response.equalsIgnoreCase("y"))
{
continue;
}
}
}
System.out.println("Your Guess is in the word");
}
if(guesses == guesses - 1)
{
//System.out.print(spaces.split("\\s").length);
//System.out.println("Your Guess is in the word");
//System.out.println();
//System.out.println("Updated word " + guess);
//System.out.println("Guesses Remaining: " + guesses);
}
}
}
}
In the example I used the difficulty was set to easy.
There is a bug here:
if (Character.toLowerCase(newWord.charAt(x)) != letterInput.charAt(0))
{
guesses= guesses - 1;
System.out.println("Your letter was not found in spaces you provided");
System.out.println("Guesses Remaining: " + guesses);
}
You cannot print the message directly because you need to make sure all spaces are not matched. This should be work:
public class HangmanBeta {
private static final boolean testingMode = true;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
keyboard.useDelimiter("\\n");
while (true) {
System.out.println("Enter your difficulty: Easy (e), Intermediate (i), or Hard (h)");
String diff = keyboard.next();
int amountOfSpaces = 0;
String response = "";
String guess = "";
String newGuess = "";
String letterInput = "";
int count = 0;
String newWord = "loops";//RandomWord.newWord();
int guesses = 0;
for (int i = 0; i < newWord.length(); i++) {
guess = newWord.replaceAll("[^#]", "-");
}
if ((diff.equalsIgnoreCase("e")) || (diff.equalsIgnoreCase("i")) || (diff.equalsIgnoreCase("h"))) {
if (diff.equalsIgnoreCase("e")) {
guesses = 15;
}
if (diff.equalsIgnoreCase("i")) {
guesses = 12;
}
if (diff.equalsIgnoreCase("h")) {
guesses = 15;
}
if (testingMode == true) {
System.out.println("The secret word is:" + " " + newWord);
}
System.out.println("The word is:" + " " + guess);
while (!newWord.equalsIgnoreCase(guess))
innerloop:
{
while (true) {
System.out.println("Please enter the letter you want to guess");
letterInput = keyboard.next();
letterInput = Character.toString(letterInput.charAt(0));
if (!Character.isLetter(letterInput.charAt(0))) {
System.out.println("Your input is not valid, try again");
break;
}
if (letterInput.equalsIgnoreCase("solve")) {
System.out.println("Please solve the answer:");
String userSolve = keyboard.next();
if (!userSolve.equalsIgnoreCase(newWord)) {
System.out.println("That is not the secret word");
guesses = guesses - 1;
System.out.println("Guesses remaining: " + guesses);
} else {
System.out.println("You win!");
System.out.println("You have guessed the word! Congratulations");
System.out.println("Would you like to play again? Yes(y) or No (n)");
response = keyboard.next();
if (response.equalsIgnoreCase("n")) {
System.exit(0);
}
if (response.equalsIgnoreCase("y")) {
continue;
}
}
}
System.out.println("Please enter the spaces you want to check (separated by spaces)");
String spaces = keyboard.next();
amountOfSpaces = spaces.length();
if (diff.equalsIgnoreCase("e")) {
if (amountOfSpaces != 7) {
System.out.println("Your input is not valid, try again");
break innerloop;
}
}
if (diff.equalsIgnoreCase("i")) {
if (amountOfSpaces != 5) {
System.out.println("Your input is not valid, try again");
break innerloop;
}
}
if (diff.equalsIgnoreCase("h")) {
if (amountOfSpaces != 3) {
System.out.println("Your input is not valid, try again");
break innerloop;
}
}
int numSpacesLeft = spaces.split("\\s").length;
for (String a : spaces.split("\\s")) {
int x = Integer.valueOf(a);
if (x > guess.length()) {
System.out.println("Your input is not valid, try again");
break innerloop;
}
if (Character.toLowerCase(newWord.charAt(x)) == letterInput.charAt(0)) {
//System.out.println("Guess is correct for position " + x);
guess = guess.substring(0, x) + letterInput + guess.substring(x + 1, guess.length());
}
numSpacesLeft--;
if (Character.toLowerCase(newWord.charAt(x)) != letterInput.charAt(0)) {
if (numSpacesLeft == 0) {
guesses = guesses - 1;
System.out.println("Your letter was not found in spaces you provided");
System.out.println("Guesses Remaining: " + guesses);
}
}
if (guesses == 0) {
System.out.println("You have failed to guess the word....:(");
System.out.print("Would you like to play again? Yes(y) or No(n)");
response = keyboard.next();
if (response.equalsIgnoreCase("n")) {
System.exit(0);
}
if (response.equalsIgnoreCase("y")) {
continue;
}
}
}
}
if (newWord.equalsIgnoreCase(guess)) {
System.out.println("You win!");
System.out.println("You have guessed the word! Congratulations");
System.out.println("Would you like to play again? Yes(y) or No (n)");
response = keyboard.next();
if (response.equalsIgnoreCase("n")) {
System.exit(0);
}
if (response.equalsIgnoreCase("y")) {
continue;
}
}
}
System.out.println("Your Guess is in the word");
}
if (guesses == guesses - 1) {
//System.out.print(spaces.split("\\s").length);
//System.out.println("Your Guess is in the word");
//System.out.println();
//System.out.println("Updated word " + guess);
//System.out.println("Guesses Remaining: " + guesses);
}
}
}
}
Hop this could help you!

if a user inputs a letter instead of a number tell them it's not a number

I'm making a guessing game, all the code works fine except for that I want them to make a number to guess between, I can't seem to figure out how to make it so that if the user inputs a letter like "d" instead of a number like "15" it will tell them they can't do that.
Code:
import java.util.Scanner;
import java.util.Random;
public class GuessingGame {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random rand = new Random();
while (true) {
System.out.print("Pick a number: ");
int number = input.nextInt();
if (number != int) {
System.out.println("That's not a number");
} else if (number == int) {
int random = rand.nextInt(number);
break;
}
}
System.out.println("You have 5 attempts to guess the number or else you fail. Goodluck!");
System.out.println("");
System.out.println("Type 'begin' to Begin!");
System.out.print("");
String start = input.next();
if (start.equals("begin")) {
System.out.print('\f');
for(int i=1; i<6; i++) {
System.out.print("Enter a number between 1-" + number + ": ");
int number = input.nextInt();
if (number > random) {
System.out.println("Too Big");
System.out.println("");
} else if (number < random) {
System.out.println("Too Small");
System.out.println("");
} else if (number == random) {
System.out.print('\f');
System.out.println("Correct!");
break;
}
if (i == 5) {
System.out.print('\f');
System.out.println("You have failed");
System.out.println("Number Was: " + random);
}
}
} else if (start != "begin") {
System.out.print('\f');
System.out.println("Incorrect Command");
System.out.println("Please Exit Console And Retry");
}
}
}
use try catch
for example
try{
int a=sc.nextInt();
}catch(Exception e){
System.out.println("not an integer");
}
You could use nextLine() instead of nextInt() and check the out coming String if it matches() the regular expression [1-9][0-9]* and then parse the line with Integer.valueOf(str).
Like:
String str=input.nextLine();
int i=0;
if(str.matches("[1-9][0-9]*"){
i=Integer.valueOf(str);
} else {
System.out.println("This is not allowed!");
}
I hope it helps.
Do something like this:
Scanner scan = new Scanner(System.in);
while(!scan.hasNextInt()) { //repeat until a number is entered.
scan.next();
System.out.println("Enter number"); //Tell it's not a number.
}
int input = scan.nextInt(); //Get your number here

How to replay basic High Low game?

I am almost finished with my second Java assignment for class, but I am stuck on how to take the user's last choice and either play again or quit. Any ideas?
import java.util.Random;
import java.util.Scanner;
public class HighLow {
public static void main(String[]args) {
Random randomNumber = new Random();
int answer = randomNumber.nextInt(100) + 1;
int numberOfTries = 0;
Scanner userInput = new Scanner(System.in);
String userGuess = null;
boolean gameWin = false;
do {
while (!gameWin) {
System.out.println("Welcome to the guessing game, guess a number between 1 - 100 or type 'quit' to exit: ");
userGuess = userInput.nextLine();
numberOfTries++;
if (userGuess.equals("quit"))
break;
if (Integer.parseInt(userGuess) == answer) {
gameWin = true;
} else if (Integer.parseInt(userGuess) < answer) {
System.out.println("Your guess is too low");
} else if (Integer.parseInt(userGuess) > answer) {
System.out.println("Your guess is too high");
}
}
if (userGuess.equals("quit")) {
System.out.println("You choose to quit! Thanks for playing");
System.out.println("The number was " + answer);
System.exit(0);
}
System.out.println("The number was " + answer);
System.out.println("It took you " + numberOfTries + " tries");
System.out.println("You win! Play again(type: yes or no)");
}
while (userGuess.equals("yes"));
userInput.nextLine();
}
}
}
The problem is because you have userInput.nextLine() prompt for the user to play again or not outside of the game loop and it isn't assigned to any value. I am referring to this section...
System.out.println("The number was " + answer);
System.out.println("It took you " + numberOfTries + " tries");
System.out.println("You win! Play again(type: yes or no)");
}
while (userGuess.equals("yes"));
userInput.nextLine(); <---
}
To fix this problem you simply need to assign the final input call to userGuess and place it back into the game loop like so.
System.out.println("The number was " + answer);
System.out.println("It took you " + numberOfTries + " tries");
System.out.println("You win! Play again(type: yes or no)");
userGuess = userInput.nextLine();
}
while (userGuess.equals("yes"));
}
Doing this will assign the play again value you prompt the user for into the variable that your testing with the do-whileloop. In your original, you had the condition testing for a value that userGuess wasn't going to be storing and instead prompting the user for that option AFTER the loop would have been exited instead of inside where it needs to be.
To reset the values for the next game, you can simply move the variables' initialization into the game loop at the top like so...
import java.util.Random;
import java.util.Scanner;
public class HighLow {
public static void main(String[]args) {
Random randomNumber = new Random();
int numberOfTries, answer;
Scanner userInput = new Scanner(System.in);
String userGuess;
boolean gameWin;
do {
answer = randomNumber.nextInt(100) + 1;
gameWin = false;
userGuess = null;
numberOfTries = 0;
while (!gameWin) {
System.out.println("Welcome to the guessing game, guess a number between 1 - 100 or type 'quit' to exit: ");
userGuess = userInput.nextLine();
numberOfTries++;
if (userGuess.equals("quit"))
break;
if (Integer.parseInt(userGuess) == answer) {
gameWin = true;
} else if (Integer.parseInt(userGuess) < answer) {
System.out.println("Your guess is too low");
} else if (Integer.parseInt(userGuess) > answer) {
System.out.println("Your guess is too high");
}
}
if (userGuess.equals("quit")) {
System.out.println("You choose to quit! Thanks for playing");
System.out.println("The number was " + answer);
System.exit(0);
}
System.out.println("The number was " + answer);
System.out.println("It took you " + numberOfTries + " tries");
System.out.println("You win! Play again(type: yes or no)");
userGuess = userInput.nextLine();
}
while (userGuess.equals("yes"));
}
}
}
this way every time the game loops through, all the values will be reset at the beginning of the new game loop.
Also you should close the Random object and Scanner object at the end of the entire program using close() on each instance.
You need to initialize most of your variables and call userInput.nextLine(); inside your outer loop. Untested suggestion:
import java.util.Random;
import java.util.Scanner;
public class HighLow {
public static void main(String[]args) {
String userGuess = null;
do {
Random randomNumber = new Random();
int answer = randomNumber.nextInt(100) + 1;
int numberOfTries = 0;
Scanner userInput = new Scanner(System.in);
boolean gameWin = false;
while (!gameWin) {
System.out.println("Welcome to the guessing game, guess a number between 1 - 100 or type 'quit' to exit: ");
userGuess = userInput.nextLine();
numberOfTries++;
if (userGuess.equals("quit"))
break;
if (Integer.parseInt(userGuess) == answer) {
gameWin = true;
} else if (Integer.parseInt(userGuess) < answer) {
System.out.println("Your guess is too low");
} else if (Integer.parseInt(userGuess) > answer) {
System.out.println("Your guess is too high");
}
}
if (userGuess.equals("quit")) {
System.out.println("You choose to quit! Thanks for playing");
System.out.println("The number was " + answer);
System.exit(0);
}
System.out.println("The number was " + answer);
System.out.println("It took you " + numberOfTries + " tries");
System.out.println("You win! Play again(type: yes or no)");
}
userInput.nextLine();
while (userGuess.equals("yes"));
}
}
}

How to ask user to Play Again....Guess Game

I'm making a simple guess game but I don't know how to ask the player if the want to play the game again.Everytime the game ends I have to run the game again so I want to add this feature to it.I looked in some other posts but they didn't help.Here's the code:
import java.util.*;
public class guessNumber{
private static Scanner userInput = new Scanner(System.in);
public guessNumber(){
System.out.println("~~~Guess Game~~~");
}
public void guessGame(){
System.out.println("Enter the maximum number:");
int maxNum = userInput.nextInt();
System.out.println("Guess a number between 0 and " + maxNum + ":");
int randomNumber = (int) (Math.random() * maxNum);
boolean gameOn = true;
int numberOfTries = 0;
while(gameOn){
boolean printOthers = true;
numberOfTries++;
int number = userInput.nextInt();
if(number > maxNum){
System.out.println("Please enter a number between 0 and " + maxNum + ".");
printOthers = false;
}
if(printOthers){
if(number == randomNumber){
System.out.println("=================================");
System.out.println("You guessed the right number xD.");
System.out.println("Your tried " + numberOfTries + " times.");
System.out.println("=================================");
}else if(number > randomNumber){
System.out.println("Try a lower number");
}else if(number < randomNumber){
System.out.println("Try a higher number");
}
else{
System.out.println("Please enter a number between 0 and " + maxNum + ".");
}
}
}
}
public static void main(String[] args){
guessNumber guess = new guessNumber();
guess.guessGame();
}
}
In your main use a while loop. In the loop first call your guessGame() then, similarly to how you ask to enter a number, you ask if they want to play again (Y/N ?) and if they say no you break the loop otherwise you go ahead...
Add your calling method in main method with in a while loop
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
do{
//call your game
System.out.println("Do you want to play again. Press y");
}
while(scanner.next().equals("y"));

Guessing Game, with a While loop

i'm currently trying to create a while loop for my program, a Guessing game. I've set it up so the user can create a max value i.e 1-500 and then the user can proceed to guess the number. When the number has been guessed, the User can press 1, to close, anything else to continue running the loop again.
My problem, is that the code gives me an error when trying to continue the loop, no compiling errros
This is my Code:
import java.util.Random;
import java.util.Scanner;
public class Gættespil2
{
public static void main(String[] args)
{
Random rand = new Random();
int TAL = rand.nextInt(20) + 1;
int FORSØG = 0;
Scanner input = new Scanner (System.in);
int guess;
int loft;
boolean win = false;
boolean keepPlaying = true;
while ( keepPlaying )
{
Scanner tastatur = new Scanner(System.in);
System.out.print("Indsæt loftets højeste værdi : ");
loft = tastatur.nextInt();
TAL = (int) (Math.random() * loft + 1);
while (win == false)
{
System.out.println(" Gæt et tal mellem 1 og "+ loft + "):: ");
guess = input.nextInt();
FORSØG++;
if (guess == TAL)
{
win = true;
}
else if (guess < TAL)
{
System.out.println("Koldere, gæt igen");
}
else if (guess > TAL) {
System.out.println("Varmere, Gæt igen!!");
}
}
System.out.println(" Tillykke du vandt...endeligt!!! ");
System.out.println(" tallet var" + TAL);
System.out.println(" du brugte " + FORSØG + " forsøg");
System.out.println("Slut spillet? tast 1.");
System.out.println("tryk på hvadsomhelst for at spille videre");
int userInt = input.nextInt();
if( userInt == 1)
{
keepPlaying = false;
}
}
}
}
Simple answer. You didn't initialize all the necessary values within your 'keepPlaying' loop before beginning a second round after the player successfully completed the first round. See annotations to your code, below:
import java.util.Random;
import java.util.Scanner;
public class GuessingGame
{
public static void main(String[] args)
{
Random rand = new Random();
int TAL = rand.nextInt(20) + 1;
int FORSØG = 0;
Scanner input = new Scanner (System.in);
int guess;
int loft;
boolean win = false;
boolean keepPlaying = true;
while ( keepPlaying )
{
Scanner tastatur = new Scanner(System.in);
System.out.print("Enter a maximum limit: ");
loft = tastatur.nextInt();
TAL = (int) (Math.random() * loft + 1);
// *** LOOK HERE ***
// Reset the 'win' flag here, otherwise the player receives an
// automatic win on all subsequent rounds following the first
win = false;
while (win == false)
{
System.out.println("Guess the number between one and "+ loft + "):: ");
guess = input.nextInt();
FORSØG++;
if (guess == TAL)
{
win = true;
}
else if (guess < TAL)
{
System.out.println("Colder, guess again!");
}
else if (guess > TAL) {
System.out.println("Warmer, guess again!");
}
}
System.out.println("You've found the number!");
System.out.println("The number was: " + TAL + ".");
System.out.println("You guessed " + FORSØG + " times.");
System.out.println("To quit, enter 1.");
System.out.println("Provide any other input to play again.");
int userInt = input.nextInt();
if( userInt == 1)
{
keepPlaying = false;
}
}
}
}
Sorry for the translation into English -- I had to make sure I was reading things correctly. You might also want to substitute "higher" and "lower" for "warmer" and "colder." "Warmer" and "colder" tend to suggest a proximity to the correct answer, as opposed to the direction in which that correct answer lies.

Categories