Incompatible type error for string[]

945 views Asked by At

Hi getting an error and don't know why. Here my code for a challenge.

    public class Solution {
    static void displayPathtoPrincess(int n, String [] grid){

    }
    public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int m;
    m = in.nextInt();
    String grid[] = new String[m];
    for(int i = 0; i < m; i++) {
        grid[i] = in.next();


    }
    int[] x;
    x = new int[m-1];
    x[0] = 0;
    String p;
    String single[];
    single = new String[(m*m)];
    for(int i = 0; i < (m); i++){
    for(int b = 0; b <= m; b++){          
        single[b] = (grid[i].split("(?!^)"));

            System.out.println(p);
    }


    } 




displayPathtoPrincess(m,grid);
}
}

The code is not neat or anywhere near complete but when I run it I get this error:

Solution.java:29: error: incompatible types 
single[b] = (grid[i].split("(?!^)")); 
^ 
required: String 
found: String[] 
1 error 

I then tried using a regular string thats not an array didnt work. I then tried to just put in a string where grid[i] is and that also didnt work. Im stuck any help is appreciated!

4

There are 4 answers

7
afzalex On BEST ANSWER

The split() method returns an array String[] and you are trying to insert array into String.

Just edit your code to this :

String single[][];
single = new String[(m * m)][];
for (int i = 0; i < (m); i++) {
    for (int b = 0; b <= m; b++) {
        single[i*m+b] = (grid[i].split("(?!^)"));
        System.out.println(p);
    }
}
displayPathtoPrincess(m, grid);
0
Codebender On

The error is because the split() method returns a String array String[]. But you are trying to assign it to a String single[b].

Edit: single[b] is not an array. It's just a regular string. single is an array.

0
Juned Ahsan On

String split method returns an array and you cannot assign an array to string :

single[b] = (grid[i].split("(?!^)")); 

hence the error. Probably you need to define single as two dimensional array and use it accordingly.

0
Tim Biegeleisen On

Here is what you were intending to do:

String[] single = grid[i].split("(?!^)");

When you make the call to String.split() Java will return an already allocated String[] array.

Unfortunately, you never finished your code so we are limited from helping you much more than this.