nonlinearone1105 nonlinearone1105 - 1 year ago 112
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[]>();

for(int i = 0; i < height; i++) {
for(int j = 0; j < width; j++) {
keyboard.put(, [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 Source


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

to something like

keyboard.put(, new Integer[] {i, j});

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download