Comparing two dimensional array to one dimensional array in Java
Does anyone know why this won't compile?
public class ArrayCompare{
public static void main (String []args){
String words= "Hello this is a test";
String delimiter=" ";
String [] blocker=words.split(delimiter);
String [][] grid= new String [100][100];
grid[0]="Hello";
if (grid[0].equals(blocker[0])){
System.out.print("Done!");
}
}
}
I would like to perform this comparison function using a 2 dimensional array. I am newbie! Please help if you can. Thanks in advance!
Try the following:
grid[0][0]="Hello";
grid
- two-dimensional array. For the same reason, you need to do the following:
if (grid[0][0].equals(blocker[0]))
It won't compile because grid [0] is not a string type. It is of type String [] (Array). The variable grid[0]
actually points to an array String[100]
.
You are trying to assign the string "Hello" to an array with
grid[0]="Hello";
...
If you want to assign a string to a location in grid
, you must specify two indices (the following): the following:
grid[0][0]="Hello";
May I suggest using eclipse or BlueJ to modify Java code? so that such basic errors are displayed in real time and well explained?
grid[0]
is a type String[]
, not String
. So your code should look like this
grid[0] = new String[100];
grid[0][0] = "Hello";
if (grid[0][0].equals(bloker[0])) {
//your logic...
}
String [][] grid= new String [100][100];
grid[0]="Hello";
There is your problem. You are trying to assign a string to an array of strings. Think of a 2d array as an array of arrays.
You probably want something like
grid[0][0]="Hello!";
grid is a 2d array. you cannot do like d [0] = "hello". So if you want to assign a value at position 0
d[0][0] = "Hello";
if (grid[0][0].equals(blocker[0])){
System.out.print("Done!");
}
First, you cannot assign a value to an element of a multidimensional array using a single index
grids [0] = "Hello";
you need to specify both indices like grid [0] [0] = "Hello" this will set the 0th element of the 0th row to Hello
Likewise, at compile time if (grid [0] .equals (blocker [0])) {System.out.print ("Done!"); you must pass the same indices here (you cannot compare String to Array object) if (grid [0] [0] .equals (blocker [0])) {System.out.print ("Done!");