简体   繁体   中英

generating value between random numbers

This is almost a re-post from an earlier question i had, but i have been struggling to point out where the problem could be, but I can't still manage the error.

I have google around for " generating value between random numbers " and found this post How do I generate a random value between two numbers

And it feels like im on the right path but I get still 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:29)

as told the error points out my row 29

int randomInt = randomGenerator.nextInt(lastGuess);

Any suggestions fellows?

Random randomGenerator = new Random();
String result = "";

int[] myIntArray = new int[10];
int i = 0;
int lastGuess = 1;
result = checkWhichNumberThisIs(0);

while (!result.equals("Equal")) {
    if (result.equals("Higher")) {
        int randomInt = randomGenerator.nextInt((10 - lastGuess + 1)) + lastGuess;

        lastGuess = randomInt;
        result = checkWhichNumberThisIs(randomInt);

        System.out.println(lastGuess + " higher");

    } else if (result.equals("Lower")) {

        int randomInt = randomGenerator.nextInt(lastGuess);

        System.out.println(randomInt + " array");
        lastGuess = randomInt;
            if (myIntArray.equals(randomInt)) {
                result = checkWhichNumberThisIs(randomInt);

                System.out.println(lastGuess + " lower");
            }
        }

    myIntArray[i] = lastGuess;
    i++;

}

This is obviously "homework" or a "learn exercise" so here's a "recipe" for finding the problem and fixing it:

  1. Start your IDE and switch to the debugger
  2. Set a breakpoint at the first line of the method
  3. Start debugging, and when the program hits the break point, single step it and watch how the lastGuess changes.
  4. Develop a mental picture of what is happening (and why), and compare that with your mental picture of how you want the program to do.
  5. Think about how to fix it ...

Now we could do this for you ... but >>you<< would next to nothing in the process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM