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.
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
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
When we call split function of String return the String[]
. So c[j]
(which is of type String
) can't be equal to 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]);
}
}