需要常量表达式?(Java switch语句)

Pat*_*zyk 3 java switch-statement

我不知道是什么导致了这个错误.我的老师和我老去了,找不到什么问题.

import java.util.Scanner;
public class MailAssignment
{
public static void main(String [] args){

    Scanner userinput = new Scanner(System.in);
    char p;
    char f;
    double price = 0;
    System.out.println("First class or priority?");
    char type = userinput.next().charAt(0);
    System.out.println("How much does the package weigh? (in ounces)");
    double weight = userinput.nextDouble();

    switch (type){
     case p:
     if (weight > 16)
        price = weight * 3.95;

        else if (weight > 32) 
            price = (1.20 * (weight / 16));
       else
            price = 3.50 * weight;


        break;


     case f: 
     if (weight < 1 )
     price = 0.34;

     else if ( weight > 1)
     price = 0.34 + (weight * 21);

     else if (weight > 13)
     price = weight * 3.95;

        else if (weight > 32) 
            price = 1.20 * (weight / 16);
        else
            price = 3.50 * weight;

            break;

        }     

    System.out.println("Your price is: " +price);
    }
}
Run Code Online (Sandbox Code Playgroud)

它在编译时抛出一个"需要常量表达式"错误并指向case p:line,但是,它也会抛出f:如果我切换它们,那么我必须完全关闭它.

Jon*_*eet 9

是的,case表达式必须是常量(或枚举常量名称) - 您不能使用变量.有关更多详细信息,请参阅Java语言规范部分14.11(switch语句).(你甚至没有初始化变量,所以不清楚你预期会发生什么,说实话.)

你的意思是:

case 'p':
    ...

case 'f':
    ...
Run Code Online (Sandbox Code Playgroud)

?这将匹配您的input(type)与字符文字 'p'和'f'.

(顺便说一句,如果这让老师感到难过,我担心他们教Java的程度是多么合适.这是相当基本的东西.)