前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >java 常量表达式,需要常量表达式? (Java switch语句)[通俗易懂]

java 常量表达式,需要常量表达式? (Java switch语句)[通俗易懂]

作者头像
全栈程序员站长
发布2022-11-11 11:05:13
8080
发布2022-11-11 11:05:13
举报
文章被收录于专栏:全栈程序员必看

大家好,又见面了,我是你们的朋友全栈君。

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

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/187886.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年9月29日 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档