1. Member
Join Date
May 2013
Posts
20
Rep Power
0

## Easier way?

Just finished a small guessing game. Was just wondering, is there a simpler way to write this? It seems so...ugly.
Java Code:
```import java.util.Scanner;

public class Guess {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int num;
System.out.println("Guess the number. It's a whole number between 1-100. You get 5 tries.");
num = in.nextInt();
// The number is 42. The meaning of life. :)
if (num == 42) {
System.out.println("You're right!");
} else {
System.out.println("You're wrong! Try again. You've got 4 more guesses.");
num = in.nextInt();
if (num == 42) {
System.out.println("You're right!");
} else {
System.out.println("You're wrong! Try again. You've got 3 more guesses.");
num = in.nextInt();
if (num == 42) {
System.out.println("You're right!");
} else {
System.out.println("You're wrong! Try again. You've got 2 more guesses.");
num = in.nextInt();
if (num == 42) {
System.out.println("You're right!");
} else {
System.out.println("You're wrong! Try again. This is your last try!");
num = in.nextInt();
if (num == 42) {
System.out.println("You're right!");
} else {
System.out.println("You're wrong. Sorry, you're out of tries!");
}
}
}
}
}
in.close();
}
}```

2. ## Re: Easier way?

Looks like a job for a while loop or a do-while loop

3. Member
Join Date
May 2013
Posts
20
Rep Power
0

## Re: Easier way?

Hah, thanks! Wrote this after reading that:
Java Code:
```import java.util.Scanner;

public class GuessRevamped {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int num;
System.out.println("Guess the number. It's a whole number between 1-100. You get 5 tries.");
num = in.nextInt();
while (num != 42) {
System.out.println("You're wrong! Try again!");
num = in.nextInt();
}
if (num == 42) {
}
}
}```
How would I set a 5-guess limit, though?

4. ## Re: Easier way?

Use the Random class to randomly generate a number to guess instead of it being 42 all the time.

You can use more than one condition for the while loop.
Java Code:
```while(x && y)
while(x || y)
while(x && y || z)
etc```

5. Member
Join Date
May 2013
Posts
20
Rep Power
0

## Re: Easier way?

I'm not seeing how that would help me set a 5-guess limit?
Are you saying I set how many times the while loop runs in the condition?

7. Member
Join Date
May 2013
Posts
20
Rep Power
0

## Re: Easier way?

Alright, thanks!

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•