mercredi 27 janvier 2016

Random integer from an array

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.




Aucun commentaire:

Enregistrer un commentaire