只是想知道如何为扫描仪对象设置输入范围,然后将其传输值并将其输入到2d数组中。
我能够设置随机数生成器的范围,但我不知道如何将相同的概念应用于扫描仪对象
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Random random = new Random();
int rows = 3;
int columns = 5;
System.out.println("Enter array elements : ");
int arry1[][] = new int[rows][columns];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns-2; j++)
{
arry1[i][j] = sc.nextInt();
}
}
arry1[0][3] = random.nextInt(50-10+1)+10;
arry1[1][3] = random.nextInt(50-10+1)+10;
arry1[2][3] = random.nextInt(50-10+1)+10;
int sum1 = 0;
int sum2 = 0;
int sum3 = 0;
sum1 = arry1[0][0]+arry1[0][1]+arry1[0][2]+arry1[0][3];
sum2 = arry1[1][0]+arry1[1][1]+arry1[1][2]+arry1[1][3];
sum3 = arry1[2][0]+arry1[2][1]+arry1[2][2]+arry1[2][3];
arry1[0][4] = sum1;
arry1[1][4] = sum2;
arry1[2][4] = sum3;
System.out.print("DISPLAYING ARRAY:");
System.out.println();
for (int[] x1 : arry1) {
for (int y1 : x1) {
System.out.print(y1 + " ");
}
System.out.println();
}
}
}
答案 0 :(得分:0)
添加检查值是否在范围内。
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Random random = new Random();
int rows = 3;
int columns = 5;
System.out.println("Enter array elements : ");
int arry1[][] = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns - 2; j++) {
int input;
do {
input = sc.nextInt();
} while (input < 0 || input > 3);
arry1[i][j] = input;
}
}
arry1[0][3] = random.nextInt(50 - 10 + 1) + 10;
arry1[1][3] = random.nextInt(50 - 10 + 1) + 10;
arry1[2][3] = random.nextInt(50 - 10 + 1) + 10;
int sum1 = 0;
int sum2 = 0;
int sum3 = 0;
sum1 = arry1[0][0] + arry1[0][1] + arry1[0][2] + arry1[0][3];
sum2 = arry1[1][0] + arry1[1][1] + arry1[1][2] + arry1[1][3];
sum3 = arry1[2][0] + arry1[2][1] + arry1[2][2] + arry1[2][3];
arry1[0][4] = sum1;
arry1[1][4] = sum2;
arry1[2][4] = sum3;
System.out.print("DISPLAYING ARRAY:");
System.out.println();
for (int[] x1 : arry1) {
for (int y1 : x1) {
System.out.print(y1 + " ");
}
System.out.println();
}
}