大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。
Jetbrains全系列IDE稳定放心使用
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.)
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/187886.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...