I'm fairly new to Java and I'm just practicing my skills using multiple classes and using System.out.println.
I'm trying to make a program in which you have a 'conversation' with the computer. What I'd like to try and do is instead of the computer having the same age every time the console is run, use an array to list a load of random ages, which will then be randomly selected. In my computer class I've got:
static int [] compAge = {19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31};
and in my main conversation class, I've got:
int Uage = input.nextInt(); // (Uage is user age)
System.out.println("That's cool! You're " +Uage+ ". I'm " + (Computers age here) + " myself. Where do you live?");
I've read around a bit and found code such as
compAge[new Random().nextInt(compAge.length)]
But in all honestly my knowledge of arrays and using the random function (I have imported it) is very limited and I'm not really sure where to go.
Any help would be massively appreciated. Thanks all.
The
new Random().nextInt()
generates a random positive number. If you use thecompAge.length()
, you set the max value (exclusively, so this will not be picked ever).That way, you get a random age everytime you start your program.
If you want to select ramdomly from array use this:
With this you have random index of array:
And to display to value like this:
Here is the complete code:
Use Math.Random instead:
It will give you a number between 0 and 12 and add 19 to it! The nice thing is that you have to change only the values here to change the range of age and not add values to an array.
You're looking to generate a random number. The general usage of Math.random is: