سؤال

I'm a newbie at Java, and I kept getting the case expressions must be constant expressions error, can someone please help? This is my code:

import java.util.Scanner;

public class IDlookup {
public void IDlookup(){
    String Stone = "ID - 1";
    String Granite = "ID - 1:1";
    //System.out.println("Hai"); //TESTER
    System.out.println("Please enter the block/item name here");
    Scanner IDselectO = new Scanner(System.in);
    String IDselect;
    IDselect = IDselectO.next();

    switch(IDselect){
    case Stone:
        System.out.println(Stone);
        break;
    case Granite:
        System.out.println(Granite);
    }



}

}
هل كانت مفيدة؟

المحلول

The error is pretty clear, declare Stone and Granite as constants

public class IDlookup {
    private final static String STONE = "ID - 1";
    private final static String GRANITE = "ID - 1:1";
        ...
}

نصائح أخرى

Make your Strings stone and granite final to fix your issue.

You also probably want to look up:

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top