Robert Nelson :
I have a code I need to set from 0-100 and have it be a possibility to have zero be the right answer. I have set my Final ints to MAX(100)/MIN(0). But 0 is never the right answer. I'm 4 years into coding with 2 years experience in Java, but it seems that any problem 1-100 or 1- any other MAX is fine. Please help, or explain if 0 isn't an allowed selection.
import java.util.Random;
import java.util.Scanner;
public class GuessingGame {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random generator = new Random();
int MIN = 0;
int MAX = 100;
int answer;
int guess;
String another = "y";
boolean flag = false;
boolean anotherFlag = true;
while(anotherFlag){
answer = generator.nextInt(MAX) + 1;
System.out.println("I'm thinkin of a number between 0 and " + MAX );
System.out.println("Can you guess what it is? \n");
flag = false;
while(!flag) {
guess = scan.nextInt();
if(guess == answer){
System.out.println("You guessed correctly");
flag = true;
} else{
System.out.println("That was wrong, try again.");
}
}
System.out.println("Want to Play again?(y/n)");
another = scan.next();
if(another.equalsIgnoreCase("y") == true){
anotherFlag = true;
} else{
anotherFlag = false;
}
}
Thank you for your help.
TrivediM :
It seems that the problem is with
answer = generator.nextInt(MAX) + 1;
Your answer range is 1 - MAX.
if you want to generate a random number between 0 - MAX, where MAX = 100. You should write-
answer = generator.nextInt(MAX+1);
Because as per Java API (java v8),
public int nextInt(int bound)
returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)