需要常量表达式? (Java switch语句) [英] Constant expression required? (Java switch statement)

查看:882
本文介绍了需要常量表达式? (Java switch语句)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道导致此错误的原因。我的老师和我去了,找不到有什么问题。

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

当它出现时,它会抛出需要常量表达式错误编译,它指向案例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节(转换语句)了解更多详情。 (你甚至没有初始化变量,所以不清楚你预期会发生什么,说实话。)

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':
    ...

?这将匹配您的输入(类型)与字符文字 '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.)

这篇关于需要常量表达式? (Java switch语句)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆