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

2022-01-19 00:00:00 switch-statement java

我不知道是什么导致了这个错误.我和我的老师检查了一遍,找不到问题所在.

I have no idea what is causing this error. My teacher and I went over it and couldn't find what was wrong.

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);
    }
}

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

It throws a "Constant expression required" error when it's compiled and it points to the case p: line, however, it also throws it for f: if I switch them so I must be doing something completely off.

推荐答案

是的,case 表达式必须是常量(或枚举常量名)——你不能使用变量.请参阅 Java 语言规范第 14.11 节(switch 语句) 了解更多详情.(您甚至还没有初始化变量,所以说实话还不清楚您期望发生什么.)

Yes, a case expression has to be a constant (or an enum constant name) - you can't use a variable. See the Java Language Specification section 14.11 (switch statements) for more details. (You hadn't even initialized the variables, so it's not clear what you expected to happen, to be honest.)

你的意思是:

case 'p':
    ...

case 'f':
    ...

?这会将您的输入 (type) 与字符 literals 'p''f' 匹配.

? This will match your input (type) against the character literals 'p' and 'f'.

(顺便说一句,如果这难倒了你的老师,我担心他们是否适合教 Java.这是相当基本的东西.)

(As an aside, if this stumped your teacher, I have concerns about how suitable they are to be teaching Java. This is reasonably basic stuff.)

相关文章