所以我只想弄清楚一种将随机生成的数字放入数组列表的方法。我也试图将10个数字放在一行10行,总共打印出100个数字。
这就是我的尝试:
import java.util.*;
public class Part1 {
public static void main(String[]args){
int[] list = new int[100];
for(int j=0; j<9; j++){
System.out.println("");
for(int g=0; g<9; g++){
for(int i=0; i<list.length; i++){
int rand = (int )(Math.random() * 500 + 1);
System.out.print(rand + " ");
}
}
}
}
}
这是我认为我最接近它的一些权利 但这是我尝试的另一个:
import java.util.*;
public class Part1 {
public static void main(String[]args){
int[] list = new int[100];
for(int i=0; i<list.length; i++){
int rand = (int )(Math.random() * 500 + 1);
for(int j=0; j<9; j++){
System.out.println(rand + " ");
for(int g=0; g<9; g++){
System.out.print("");
}
}
}
}
}
试图了解如何将这些随机数放入数组,然后将数字打印成10行。感谢提示和/或提前帮助。
答案 0 :(得分:1)
使用一维数组:
Random rand = new Random();
int[] list = new int[100];
int count = 1;
for (int i = 0; i < list.length; i++)
{
list[i] = rand.nextInt(500) + 1;
// check if you're at the 10th number in the line
if (count % 10 > 0) System.out.print(list[i] + " "); // print on this line
else System.out.println(list[i] + " "); // print on a new line
count++;
}
使用二维数组(推荐):
Random rand = new Random();
int[][] list = new int[10][10];
for (int r = 0; r < list.length; r++)
{
for (int c = 0; c < list[r].length; c++)
{
list[r][c] = rand.nextInt(500) + 1;
System.out.print(list[r][c] + " "); // print on this line
}
// this occurs when you're done displaying each row, so skip a line.
System.out.println();
}
使用ArrayList:
Random rand = new Random();
List<Integer> list = new ArrayList<Integer>();
int count = 1;
for (int i = 0; i < 100; i++)
{
list.add(rand.nextInt(500) + 1);
// check if you're at the 10th number in the line
if (count % 10 > 0) System.out.print(list.get(i) + " "); // print on this line
else System.out.println(list.get(i) + " "); // print on a new line
count++;
}
答案 1 :(得分:0)
享受:)
import java.util.Random;
public class Uno {
public static void main(String ... args){
Random rand = new Random();
int[] a = new int[100];
for (int i=0; i<100; i++) {
a[i] = rand.nextInt();
System.out.print(a[i] + ", ");
// perform modulo division by 10 to check if 10 results have been printed and add a new line
if( (i+1)%10==0 ) { System.out.println(); }
}
}
}
答案 2 :(得分:0)
public static void main(String[]args){
int[] list = new int[100];
for(int i=0; i<list.length; i++){
int rand = (int )(Math.random() * 500 + 1);
list[i] = rand;
}
int lineNumberCounter = 0;
for(int i=0; i<list.length; i++){
if(lineNumberCounter == 10){
System.out.println();
lineNumberCounter=0;
}
System.out.print(list[i] + " ");
lineNumberCounter++;
}
}
您可以通过将上述内容修改为:
来设置和打印相同的for循环 public static void main(String[]args){
int[] list = new int[100];
int lineNumberCounter = 0;
for(int i=0; i<list.length; i++){
int rand = (int )(Math.random() * 500 + 1);
list[i] = rand;
if(lineNumberCounter == 10){
System.out.println();
lineNumberCounter=0;
}
System.out.print(list[i] + " ");
lineNumberCounter++;
}
}