I am receiving an error with this code that pops up Class file editor: source not found inside the Random.class tab. It was having issues with my line that says value =…
I am trying to create a general method the generate a random number between the two integers I pass in.
import java.util.Random;
public class RandomNumGen {
int value;
Random rand;
public RandomNumGen() {
rand = new Random();
}
public int intRandom(int min, int max) {
value = rand.nextInt(max) + min;
return(value);
}
public int choiceRandom(int first, int second, int third, int fourth) {
int random = intRandom(1, 400);
if (random < 100) {
return(first);
}else if (random > 100 && random < 200) {
return(third);
}else if (random > 200 && random < 300) {
return(fourth);
}
return(second);
}
}
Help would be appreciated,
Thanks
The “source not found” error is because it tried to open the source to
java.util.Randomto help you debug and couldn’t find it. The code looks right in that it should execute without errors;Random.nextIntwill throw anIllegalArgumentExceptionif you pass it a non-positive number, but you’re passing it 400. I don’t get any errors running that code snippet and callingchoiceRandom(1, 2, 3, 4);However, logically the code is wrong —
intRandomdoesn’t return a number betweenminandmax. You’re callingnextInt(max), which returns a number between0andmax-1, and then addingmin, making the range betweenminandmin+max-1. You’d need to returnrand.nextInt(max-min) + minIf you just want a method that takes a bunch of integers and returns one at random, a simpler implementation is: