Does anyone know why this doesn'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 function of comparison using a 2 dimensional array. I am a newbie! Please help if you can. Thanks in advance!
Try this:
grid[0][0]="Hello";
grid
is a two-dimensional array. For the same reason, you need to do this:
if (grid[0][0].equals(blocker[0]))
It won't compile because grid[0] is not String type. It is String[] (Array) type. Variable grid[0]
is actually pointing to a String[100]
array.
You are attempting to assign a string "Hello" to an array by
grid[0]="Hello";
statement.
If you want to assign a string to a location in grid
, you must provide two index(s) - following is legal:
grid[0][0]="Hello";
May I suggest using eclipse or BlueJ to edit your Java code? so that such basic errors are shown on real-time and explained well?
grid[0]
is a String[]
type, not a String
. So your code should be 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's your problem. You are trying to assign a string to a string array. Think of a 2d array as an array of arrays.
You probably want something like
grid[0][0]="Hello!";
grid is 2d array. you can't do like d[0] = "Hello". So, if you want to assign value at 0 position
d[0][0] = "Hello";
if (grid[0][0].equals(blocker[0])){
System.out.print("Done!");
}
First thing you can't assign value to the element of the multi dimensional array using single index
grid[0]="Hello";
you need to specify both the indices like grid[0][0] = "Hello" this will set the 0th element of 0th row to Hello
Likewise while compairing if (grid[0].equals(blocker[0])){ System.out.print("Done!"); you have to pass the same indices here (You cannot compare a String to a Array Object) if (grid[0][0].equals(blocker[0])){ System.out.print("Done!");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.