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!
source to share
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?
source to share
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!");
source to share