从数组随机整数 [英] Random integer from an array

查看:116
本文介绍了从数组随机整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是相当新的Java和我使用多个类,并使用System.out.println只是在练习我的技能。

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?");

我读了一下周围,发现code,如

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.

任何帮助将是大量AP preciated。感谢所有。

Any help would be massively appreciated. Thanks all.

推荐答案

使用的Math.random来代替:

Use Math.Random instead:

int age = ((int)Math.random()*13)+19;

这会给你一个数字0和12之间,并添加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.

这篇关于从数组随机整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆