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.
compAge[new Random().nextInt(compAge.length() )]
The new Random().nextInt()
generates a random positive number. If you use the compAge.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.
You're looking to generate a random number. The general usage of Math.random is:
// generates a floating point random number greater than 0
// and less than largestPossibleNumber
float randomNumber = Math.random() * largestPossibleNumber;
// generates an integer random number between greater than 0
// and less than largestPossibleNumber
int randomNumber = (int)(Math.random() * largestPossibleNumber);
// generates an integer random number greater than 1
// and less than or equal to largestPossibleNumber
int randomNumber = (int)(Math.random() * largestPossibleNumber) + 1;
Use Math.Random instead:
int age = ((int)Math.random()*13)+19;
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.
If you want to select ramdomly from array use this:
static int [] compAge = {19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31};
With this you have random index of array:
int age = new Random().nextInt(compAge.length);
And to display to value like this:
System.out.println("Random value of array compAge : " + compAge[age]);
Here is the complete code:
import java.util.Random;
import java.util.Scanner;
public class MainConversation {
public static void main (String[] args) {
Scanner input = new Scanner (System.in);
int [] compAge = {19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31};
System.out.println("Enter a random number between 0 and "+ (compAge.length-1));
int numb;
while(input.hasNextInt() && (numb = input.nextInt()) < compAge.length){
// int age = new Random().nextInt(compAge.length);
System.out.println("Random value of array compAge : " + compAge[numb]);
}
}
}