java 常量表达式,需要常量表达式? (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);

}

}

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.

解决方案

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.)

Did you mean:

case 'p':

...

case 'f':

...

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

(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.)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值