patternjavaMinor
Guess the number game
Viewed 0 times
numbergametheguess
Problem
I just started to learn Java and had to write a "guess the number" game.
Could you please review and give me some feedback?
Could you please review and give me some feedback?
public static void main(String[] args) {
System.out.println("Welcome to the guess the number game!\n");
System.out.println("Please specify the configuration of the game:\n");
Scanner input = new Scanner(System.in);
System.out.println("Range start number (inclusively):");
int startRange;
startRange = nextValidInt(input);
System.out.println("Range end (inclusively):");
int endRange;
endRange = nextValidInt(input);
System.out.println("Maximum number of attemps:");
int maxAttemp;
maxAttemp = nextValidInt(input);
System.out.println("Your Task is to guess the random number between "
+ startRange + " and " + endRange);
Random randGenerator = new Random();
int randNumber = randGenerator.nextInt((endRange - startRange + 1)
+ startRange);
int numberOfTries = 0;
System.out
.println("You may exit the game by typing; exit - you may now start to guess:");
for (numberOfTries = 0; numberOfTries randNumber) {
System.out.println("The number is smaller");
} else if (guess = maxAttemp) {
System.out.println("You reached the max Number of attempts :-/");
}
}
public static int nextValidInt(Scanner s) {
while (!s.hasNextInt() && s.hasNext()) {
System.out.println("Please provide a valid integer value!");
s.next();
}
return s.nextInt();
}
Solution
Not a full review, just a couple of points that jumped out at me:
- you often assign the value to a variable on the next line after declaring it. Just assign the value on the same line (eg
int startRange = nextValidInt(input);).
- you can declare a loop variable inside the loop:
for (int numberOfTries = 0; numberOfTries
- if (numberOfTries >= maxAttemp)
will always be true, as theforloop increasesnumberOfTriestomaxAttemp. Well, except when you won. I would remove theifand replace thebreakwith areturn.
- numberOfTries
- the
mainmethod shouldn't do anything except start your program. I would move your code to its own function. You might also want to create extra functions for initial info printing/setup gathering and the actual guessing game.
Context
StackExchange Code Review Q#66433, answer score: 6
Revisions (0)
No revisions yet.