nonlinearone1105 nonlinearone1105 - 1 month ago 10
Java Question

Illegal start of expression when adding data to HashMap

I am writing a program for an online class I'm taking. It is supposed to read a theoretical "keyboard" and three sample coding templates created using said keyboard from a text file. It is then supposed to calculate the time required to type said template based on a formula given within the problem. The formula involves assigning each "key" on the keyboard an (x,y) coordinate, which is used to calculate distance by comparing it to the (x,y) coordinate of the next character to be typed.

To do this, I am using a HashMap where the key is the ASCII character at that location on the keyboard and the value is an int array storing the (x,y) value. My program will use a character from the template to retrieve the (x,y) coordinate from the HashMap and then perform the necessary math.

The issue I'm having is that I'm getting an "illegal start of expression" error when I compile my program. The error points to the line with the keyboard.put command and I can't figure out why. Here's the relevant code to read in the keyboard characters and (x,y) coordinates:

public static void main(String[] args) throws IOException {
try(Scanner in = input(); PrintWriter out = output()) {
int width = in.nextInt();
int height = in.nextInt();
HashMap<Character, Integer[]> keyboard = new HashMap<Character, Integer[]>();

in.useDelimiter("");
for(int i = 0; i < height; i++) {
for(int j = 0; j < width; j++) {
keyboard.put(in.next(), [i,j]);
^error marked here
}
}
}
}


In researching, it looks like this error generally pops up because either an object was declared incorrectly (often because "public" was put in front of the declaration) or because of a missing ; prior to the line in question. Neither of these is the case here, so I'm stumped. Any thoughts?

Answer

Change

keyboard.put(in.next(), [i,j]);

to something like

keyboard.put(in.next().charAt(0), new Integer[] {i, j});

Because in.next() returns a String (not a Character), and you need an Integer[] which you can create as shown.

Comments