所以我想跳过数组的第一个和最后一个元素进行初始化。我做错了什么?
public static void main(String args[]) throws Exception {
//Write code here
Scanner sc = new Scanner(System.in);
System.out.println("Input Rows: ");
int m = sc.nextInt();
System.out.println("Input Columns: ");
int n = sc.nextInt();
System.out.println("Enter values: ");
int[][] arr = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (arr[i][j] == arr[0][0] || arr[i][j] == arr[m][n]) {
continue;
} else {
arr[i][j] = sc.nextInt();
}
}
System.out.println();
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
这是我的输出:
Input Rows:
3
Input Columns:
3
Entered Values:
0 0 0
0 0 0
0 0 0
答案 0 :(得分:2)
您需要更改循环内的if条件,如下所示:
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if ((i == 0 && j==0) || (i == m -1 && j == n -1)) {
continue;
} else {
arr[i][j] = sc.nextInt();
}
}
System.out.println();
}
答案 1 :(得分:2)
在这一行:
if (arr[i][j] == arr[0][0] || arr[i][j] == arr[m][n]) {
您正在测试数组中值的相等性。您应该比较您正在查看的索引是数组的开头还是结尾。 也就是说,你想比较(伪代码):
i==0 and j==0, OR i==max index in its dimension and j==max index in its dimension
我故意省略了字面答案,因为这看起来有点像家庭作业。
答案 2 :(得分:1)
您将arr[i][j]
的值与arr[0][0]
的值进行比较。您应该比较i==0 && j==0 || i==m -1 && j==n -1
当你的数组为空时,当你开始循环时,arr [i] [j]等于arr [0] [0],跳过第一个元素。但是对于下一个循环,arr [i] [j]仍然是空的,当你将它与非初始化值进行比较时,它始终为真,跳过每一步
public static void main(String args[]) throws Exception {
//Write code here
Scanner sc = new Scanner(System.in);
System.out.println("Input Rows: ");
int m = sc.nextInt();
System.out.println("Input Coloumns: ");
int n = sc.nextInt();
System.out.println("Enter values: ");
int[][] arr = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i==0 && j==0 || i==m-1 && j==n-1) {
continue;
} else {
arr[i][j] = sc.nextInt();
}
}
System.out.println();
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
答案 3 :(得分:-1)
您不需要检查数组项是否相等,您只想检查行和列是否等于最后一行和第一行。