[英]error: incompatible types: String[] cannot be converted to String
I tried taking input of a 6 by 6 matrix in java using the string split function when the string is input in the following way, and to print the matrix.当以以下方式输入字符串时,我尝试使用字符串拆分 function 在 java 中输入 6 x 6 矩阵,并打印矩阵。
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
The output that I get is我得到的 output 是
Main.java:24: error: incompatible types: String[] cannot be converted to String
c[j] = b[i].split(" ");
my code:我的代码:
import java.util.*;
import java.io.*;
class Solution {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
int a[][] = new int[6][6];
String b[] = new String[6];
for (int i = 0; i < 6; i++) {
b[i] = s.nextLine();
}
// initializing the 2d array a[][]
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 6; j++) {
String c[] = new String[6];
c[j] = b[i].split(" ");
a[i][j] = Integer.parseInt(c[j]);
}
}
// printing the input array
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 6; j++) {
System.out.print("\ta[i][j]\t");
}
}
}
}
pls, suggest how I can overcome this error请建议我如何克服这个错误
The return type of split()
function is type of array. split()
function 的返回类型是数组类型。 Because you are asking java to give me each value as separate which is separated by " "
(space).因为您要求 java 给我每个单独的值,由
" "
(空格)分隔。 So java will create an array of each value and returns you the array.因此 java 将创建一个包含每个值的数组并返回该数组。 For storing the array you need an variable of type array.
为了存储数组,您需要一个数组类型的变量。 here
c
represent an array, but c[j]
represents an single index of the array.这里
c
代表一个数组,而c[j]
代表数组的单个索引。
You can change your code like:您可以更改您的代码,如:
for (int i = 0; i < 6; i++) {
String c[] = b[i].split(" ");
for (int k = 0; k < c.length; k++) {
a[i][k] = Integer.parseInt(c[k]);
}
}
The the inputs are integer and you are converting them to integer later, I would suggest you to take input as integer like below:输入是 integer 并且您稍后将它们转换为 integer,我建议您将输入作为 integer 如下所示:
class Solution {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
int a[][] = new int[6][6];
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 6; j++) {
a[i][j] = s.nextInt();
}
}
// printing the input array
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 6; j++) {
System.out.print("\ta[i][j]\t");
}
}
}
}
When we call split function of String return the String[]
.当我们调用 String 的 split function 时,返回
String[]
。 So c[j]
(which is of type String
) can't be equal to String[]
.所以
c[j]
(它的类型是String
)不能等于String[]
。
Below code should be replaced as:下面的代码应替换为:
// initializing the 2d array a[][]
for (int i = 0; i < 6; i++) {
String[] c = b[i].split(" ");
for (int j = 0; j < 6; j++) {
a[i][j] = Integer.parseInt(c[j]);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.