【问题标题】:How to convert a 2D arrays into an integer using for each loop [duplicate]如何使用每个循环将二维数组转换为整数[重复]
【发布时间】:2019-05-22 17:49:43
【问题描述】:

使用“for each”循环将二维数组转换为整数时遇到问题

import java.util.Scanner;

公共类矩阵{ 公共静态 void main(String[] args) {

    Scanner userInput = new Scanner(System.in);

int [][] matrix = new int[2][2];

    for (int x = 0 ; x < 2 ; x++){
        for(int y = 0 ; y < 2 ; y++){
            System.out.printf("enter a number for row %d column %d : ",(x+1),(y+1));
            matrix[x][y] = userInput.nextInt();
        }
    }

for(int t : matrix){
        System.out.print(t + " ");
    }

    userInput.close();
}

}

但我得到一个错误 int[] cannot be convert to int.

【问题讨论】:

  • 对于这样的问题,你需要提供潜在的输入和对应的预期输出。
  • 始终为您的代码使用正确的格式并详细说明问题。提及您面临的问题是什么,就像@DerekPendleton 提到的那样,必须正确提及您期望的输出。

标签: java arrays multidimensional-array


【解决方案1】:

请提供@derek-pendleton 提到的示例输入和输出。

你似乎在你的 for 循环中做的是向你的行添加行。

所以如果你的二维数组看起来像这样 [ [1, 2], [3, 4] ]。然后 int t :矩阵,您的 t 将是列表,即:[1, 2] 和下一次迭代 [3, 4]。因此,您需要在其中添加另一个循环:

for (int[] t : matrix){
    for (int nr : t){
        //print(nr + something);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-10
    • 2014-04-23
    • 2019-04-28
    • 2018-08-08
    • 1970-01-01
    • 2013-01-27
    • 1970-01-01
    相关资源
    最近更新 更多