【发布时间】:2015-10-17 16:18:21
【问题描述】:
问题:
编写一个程序来创建一个大小为 20 的数组来存储整数。然后,程序应生成 1 到 7 之间的随机数并将其插入到数组中。接下来,程序应该将数组打印为输出。
一个简单的子集是一个数组的一部分,它由一组相邻的 4 个元素组成。程序会生成一个介于 0 到 19 之间的随机数,它代表数组中的位置(即索引号)。然后,程序应该从该位置打印 4 个元素。该程序应考虑数组的边界。此程序没有用户输入。
您的程序必须至少包含以下方法:
- insertNumbers,它将一个整数数组作为输入并将随机数存储在其中。
- computeLocation,生成位置随机数并返回。
程序的示例运行如下所示:
示例输出 #1:
阵列:2 7 4 3 1 5 7 2 3 6 2 7 1 3 2 4 5 3 2 6
随机位置:2
子集:4 3 1 5
示例输出 #2:
阵列:2 7 4 3 1 5 7 2 3 6 2 7 1 3 2 4 5 3 2 6
随机位置:18
子集:2 6 2 7
到目前为止,我发现了什么: 公共类 AssignmentQuestion3 {
public static int insertNumbers(int n1,int n2)
{
int min = n1;
int max = n2;
int randomNumber = min + (int) (Math.random() * (max-min)+1);
return randomNumber;
}
public static int computeLocation(int l1,int l2)
{
int min = l1;
int max = l2;
int computeLocation = min + (int) (Math.random() * (max-min) + 1);
return computeLocation;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int array[] ={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
System.out.print("Arrays: ");
for(int i = 0; i < 20; i++)
{
int random1 = insertNumbers(1, 7);
array[i] = random1;
System.out.print(array[i]+ " ");
}
【问题讨论】:
-
Stackoverflow.com != DoMyHomeWorkForFree.com :P
-
我做了一个随机数生成器,但已经被卡住了。
-
它继续打印数组,因为第一个数字将为 0,然后其余 19 位数字将是相同的数字。
-
设置计算随机数的上下限
-
向我们展示您到目前为止编写的代码,告诉我们它做了什么以及应该做什么。
标签: java arrays random numbers location