patternjavaMinorCanonical
High-Low Guessing Game
Viewed 0 times
gamehighguessinglow
Problem
The program is asking you to guess a number between 1-100 and if you guessed too low it says that in Swedish and the same goes for if it's too high and if it's the correct answer it says congratz you guessed right in Swedish.
I'd like comments about any aspects of my code.
I'd like comments about any aspects of my code.
public class Kidsprogram {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random rand = new Random();
int number = rand.nextInt(100) + 1;
System.out.println("Gissa på ett nr mellan 1 och 100");
for (int i = 1; i > -1; i++)
{
int guess;
guess = input.nextInt();
if (guess number)
{
System.out.println("Du gissade för högt");
}
else if(guess == number)
{
System.out.println("Antal gissningar: " + i);
System.out.println("Grattis du gissade rätt!");
break;
}
}
}
}Solution
Since the end condition of the loop is always true, you can just omit it:
The condition in the final
so you can use simply
There's no need to separate the declaration and initialization of the
you can do
The convention in Java is to put opening braces on the same line as the statement,
like this:
for (int i = 1; ; i++)The condition in the final
else if(guess == number) is always true,so you can use simply
else.There's no need to separate the declaration and initialization of the
guess variable,you can do
int guess = input.nextInt() which is shorter.The convention in Java is to put opening braces on the same line as the statement,
like this:
for (int i = 1; ; i++) {
int guess = input.nextInt();
if (guess number) {
System.out.println("Du gissade för högt");
} else {
System.out.println("Antal gissningar: " + i);
System.out.println("Grattis du gissade rätt!");
break;
}
}Code Snippets
for (int i = 1; ; i++)for (int i = 1; ; i++) {
int guess = input.nextInt();
if (guess < number) {
System.out.println("Du gissade för lågt");
} else if(guess > number) {
System.out.println("Du gissade för högt");
} else {
System.out.println("Antal gissningar: " + i);
System.out.println("Grattis du gissade rätt!");
break;
}
}Context
StackExchange Code Review Q#77657, answer score: 8
Revisions (0)
No revisions yet.