I’m trying to create a “secret” number finder without using a loop that counts from 1 to 10. Now what I am trying is to random out 10 numbers that if they are higher than the secret number in this case number 5 the loop will only look for number between 5 – 10 or if its lower 0-5.
Sometimes the function gives me an output that can look like this Higher: 0 Lower : 8 And then the error
Exception in thread "main" java.lang.IllegalArgumentException: n must be positive
at java.util.Random.nextInt(Unknown Source)
at test1.testvoid$TestVoidMethod.main(testvoid.java:31)
Otherwise I can get the output
Higher : 1
The secret number is: 3
Without an error.
This is as far I get. I know this is a wot, but its hard to point out where the problem could be.
import java.util.Random;
public class testvoid {
public static class TestVoidMethod {
static int secretNumber = 3;
public static void main(String[] args) {
Random randomGenerator = new Random();
String result = "";
int[] myIntArray = new int[10];
int i = 0;
int lastGuess = 0;
result = checkWhichNumberThisIs(0);
while (!result.equals("Equal"))
{
if(result.equals("Higher"))
{
int randomInt = randomGenerator.nextInt(10 - (lastGuess - 1)) + lastGuess;
lastGuess = randomInt;
result = checkWhichNumberThisIs(randomInt);
}
else if(result.equals("Lower"))
{
int randomInt = randomGenerator.nextInt(lastGuess);
lastGuess = randomInt;
if(myIntArray.equals(randomInt)){
result = checkWhichNumberThisIs(randomInt);
}
}
myIntArray[i] = lastGuess;
i++;
}
}
public static String checkWhichNumberThisIs(int numberGuess) {
String result = "";
if (secretNumber < numberGuess) {
result = "Lower";
System.out.println("Lower " + numberGuess);
}
else if (secretNumber > numberGuess) {
result = "Higher";
System.out.println("Higher " + numberGuess);
}
else if (secretNumber == numberGuess) {
result = "Equal";
System.out.println("The secret number is: " + numberGuess);
}
return result;
}
}
}