数组中的随机整数
我是Java的新手,我只是在使用多个类并使用System.out.println来练习我的技能。
我正在尝试制作一个与计算机进行“对话”的程序。 我想要尝试做的不是每次运行控制台时具有相同年龄的计算机,而是使用数组列出随机年龄的负载,然后随机选择。 在我的计算机课上,我得到了:
static int [] compAge = {19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31};
在我的主要会话课上,我有:
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?");
我已经阅读了一下,发现了诸如此类的代码
compAge[new Random().nextInt(compAge.length)]
但老实说,我对数组的知识和使用随机函数(我已经导入它)是非常有限的,我不知道该去哪里。
任何帮助都将受到大力赞赏。 谢谢大家。
compAge[new Random().nextInt(compAge.length() )]
new Random().nextInt()
生成一个随机的正数。 如果使用compAge.length()
,则设置最大值(仅限于此,因此不会选择此项)。
这样,每次启动程序时都会出现随机时间。
你想要生成一个随机数。 Math.random的一般用法是:
// 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;
请改用Math.Random:
int age = ((int)Math.random()*13)+19;
它将为您提供0到12之间的数字,并为其添加19! 不错的是,您必须仅更改此处的值以更改年龄范围,而不是向数组添加值。
如果你想从数组中选择ramdomly,请使用:
static int [] compAge = {19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31};
有了这个你有数组的随机索引:
int age = new Random().nextInt(compAge.length);
并显示如下的值:
System.out.println("Random value of array compAge : " + compAge[age]);
这是完整的代码:
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]); } } }