Reputation: 11
I've been trying to learn Java on my own for about a week, and I've decided to try and apply my (pretty limited) knowledge to making a simple guessing game.
Basically the user inputs a number between 1 and 10, and they get feedback depending on whether they guessed too high, too low, or correctly guessed a random number.
My problem is that once I run my method, I don't know how to allow for multiple guesses. Basically they guess once, and then that's it. Game over.
I'm sure it's something simple like a loop I need to implement, maybe an additional variable gets declared if they guess wrong? I don't know.
Can anyone help me out?
Here's my code:
import java.util.Scanner;
import java.util.Random;
public class GuessingGame {
public static void main(String[] args) {
//creates a new scanner object
Scanner input = new Scanner(System.in);
// randomly generates a number from 1-10
Random rand = new Random();
int myNumber = rand.nextInt(10)+1;
String tooWarm = "Too high. Try again!";
String tooCold = "Too cold. Try again!";
String bingo = "Yup! Good guess!";
boolean playing = true;
System.out.printf("What's your name? ");
String name = input.nextLine();
System.out.println("Well, " + name + ", betcha can't guess what number I'm thinking of! \nHint: it's between 1 and 10...");
int value = input.nextInt();
if (value > myNumber) {
System.out.println(tooWarm);
}
else if (value < myNumber) {
System.out.println(tooCold);
}
else {
System.out.println(bingo);
}
}
}
Upvotes: 1
Views: 653
Reputation: 803
import java.util.Scanner;
import java.util.Random;
public class GuessingGame {
public static void main(String[] args) {
//creates a new scanner object
Scanner input = new Scanner(System.in);
// randomly generates a number from 1-10
Random rand = new Random();
int myNumber = rand.nextInt(10)+1;
String tooWarm = "Too high. Try again!";
String tooCold = "Too cold. Try again!";
String bingo = "Yup! Good guess!";
boolean playing = true;
System.out.printf("What's your name? ");
String name = input.nextLine();
System.out.println("Well, " + name + ", betcha can't guess what number I'm thinking of! \nHint: it's between 1 and 10...");
while(true){
int value = input.nextInt();
if (value > myNumber) {
System.out.println(tooWarm);
}
else if (value < myNumber) {
System.out.println(tooCold);
}
else {
System.out.println(bingo);
return;
}
}
}
Upvotes: 0
Reputation: 1325
Add this to the end of your code:
...
char yN = input.nextChar();
if (yN == 'y' || yN == 'Y') {
main(null);
return;
}
}//end of main().
basically what it does is that it makes recursive calls, so that the game can be played again and again. :-)
Upvotes: 0
Reputation: 6855
just do this,
do..while makes your execution to execute atleast once.
do {
System.out.println("Enter : ");
int value = input.nextInt();
if (value > myNumber) {
System.out.println(tooWarm);
}
else if (value < myNumber) {
System.out.println(tooCold);
}
else {
System.out.println(bingo);
playing = false;
}
}
while (playing);
Upvotes: 1