为随机 2D java 数组问题创建用户输入 - OutOfBoundsException
Creating user input for randomized 2D java array issue - OutOfBoundsException
正在尝试创建一个采用用户输入的行和列的二维数组。然后数组中的数字从 0 到 100 随机化。我收到以下错误:
为数组输入行:3
为数组输入列:2
线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException:索引 3 超出长度 3 的范围
在 test2.main(test2.java:17)
这是我的代码:
import java.lang.Math;
import java.util.Scanner;
public class test2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter rows for the array: ");
int rows = scan.nextInt();
System.out.print("Enter columns for the array: ");
int columns = scan.nextInt();
int [][] myArray = new int [rows][columns];
for (rows = 0; rows < myArray.length;rows++) {
for (columns = 0; columns < myArray.length; columns++)
myArray[rows][columns] = (int) (Math.random()*100);
System.out.print(myArray[rows][columns] + "\t");
}
}
}
您应该使用单独的变量来 运行 循环。
public class Random {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter rows for the array: ");
int rows = scan.nextInt();
System.out.print("Enter columns for the array: ");
int columns = scan.nextInt();
int[][] myArray = new int[rows][columns];
for (int row = 0; row < rows; row++) {
for (int col = 0; col < columns; col++) {
myArray[row][col] = (int) (Math.random() * 100);
System.out.print(myArray[row][col] + "\t");
}
}
}
}
正在尝试创建一个采用用户输入的行和列的二维数组。然后数组中的数字从 0 到 100 随机化。我收到以下错误:
为数组输入行:3
为数组输入列:2
线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException:索引 3 超出长度 3 的范围 在 test2.main(test2.java:17)
这是我的代码:
import java.lang.Math;
import java.util.Scanner;
public class test2 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter rows for the array: ");
int rows = scan.nextInt();
System.out.print("Enter columns for the array: ");
int columns = scan.nextInt();
int [][] myArray = new int [rows][columns];
for (rows = 0; rows < myArray.length;rows++) {
for (columns = 0; columns < myArray.length; columns++)
myArray[rows][columns] = (int) (Math.random()*100);
System.out.print(myArray[rows][columns] + "\t");
}
}
}
您应该使用单独的变量来 运行 循环。
public class Random {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter rows for the array: ");
int rows = scan.nextInt();
System.out.print("Enter columns for the array: ");
int columns = scan.nextInt();
int[][] myArray = new int[rows][columns];
for (int row = 0; row < rows; row++) {
for (int col = 0; col < columns; col++) {
myArray[row][col] = (int) (Math.random() * 100);
System.out.print(myArray[row][col] + "\t");
}
}
}
}