Java Coding Question

Dross

New Member
Hi,
I have a beginner's Java coding question. I do not understand how the following two lines of code are working within the context of the overall program... (see bottom of message for context):

fortuneIndex = randini.nextInt(fortunes.length);

switch (randini.nextInt(7) % 7) {

It seems to me that the seed in the first line would be the same every time the code is run because the "fortune" array isn't determined until the end of the program. Similiarly, in the following line, wouldn't the random interger generated be the same every time since the seed (7) is the same? Also, any idea why the random int was generated in such a manner (randini.nextInt(7) % 7)? Wouldn;t it make as much sense to just use (randini.nextInt())? Any help would be greatly appreciated! Thanks :D

++++++++++++++++++++++++++++++++++++
import java.util.Random;

public class Fortune {

public static void main(String args[]) {
Random randini = new Random();
int fortuneIndex;
String day;
String[] fortunes = { "The world is going to end :-(.",
"You will have a HORRIBLE day!",
"You will stub your toe.",
"Tomorrow... is too difficult to predict" };

System.out.println("\nYou have awakened the Great Randini...");

fortuneIndex = randini.nextInt(fortunes.length);

switch (randini.nextInt(7) % 7) {

case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
break;
default:
day = "Tomorrow";
}
System.out.println("I see that on " + day);
System.out.println("\n" + fortunes[fortuneIndex]);
}

}
 
Random.nextInt(int n)
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.

so randini.nextInt(7) returns a number between 0 and 7, modding by 7 gets a number from 0 to 6. You're right, in the context of the switch statement nextInt makes about the same amount of sense, removing the % 7 would make the most sense however.
 
Back
Top