简体   繁体   English

在2d char数组Java中存储矩阵

[英]Store a matrix in 2d char array Java

I am trying to store a matrix in java 2d char array but since I can't accept the input in char, I am trying to look for the best possible solution to store in a 2d char array. 我正在尝试将矩阵存储在java 2d char数组中,但是由于我不能接受char的输入,因此我试图寻找最好的解决方案以将其存储在2d char数组中。

eg. 例如。 Matrix 矩阵

 1112
 1912
 1892
 1234

What I tried:- 我试过的

 for(int i=0; i<n; i++)
        for(int j=0; j<n; j++)
            map[i][j]=sc.next().charAt(0);

Gives wrong output. 输出错误。 Any other suggestions? 还有其他建议吗?

You need to change the code to 您需要将代码更改为

String data = "";
int count = 0;
for (int i = 0; i < n; i++) {
    if (sc.hasNext()) {
        data = sc.next();
        count = 0;
    } else {
        break;
    }
    for (int j = 0; j < n; j++)
    map[i][j] = data.charAt(count++);
}

for loop of i and j is for generating matrix indexes and since you need to read the character you first have to read token by token then iterate over their characters the other user answer fails because the user uses j loop for both matrix and chracter reading so if on the last iteration of j ie n-1(denotes matrix length not the string length) if string length is less than n-1 you will get IndexOutOfbound Exception for in.charAt(j) . i和j的for循环用于生成矩阵索引,并且由于您需要读取字符,因此您首先必须逐个令牌读取令牌,然后遍历其字符,其他用户答案将失败,因为用户将j循环用于矩阵和chracter读取,因此如果在j的最后一次迭代中即n-1(表示矩阵长度而不是字符串长度),如果字符串长度小于n-1,则将为in.charAt(j)获得IndexOutOfbound Exception。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM