[英]Constant expression required? (Java switch statement)
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. 它在编译时抛出一个“需要常量表达式”错误并指向case p:line,但是,它也会抛出f:如果我切换它们,那么我必须完全关闭它。
Yes, a case
expression has to be a constant (or an enum constant name) - you can't use a variable. 是的,
case
表达式必须是常量(或枚举常量名称) - 你不能使用变量。 See the Java Language Specification section 14.11 (switch statements) for more details. 有关更多详细信息,请参阅Java语言规范部分14.11(switch语句) 。 (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'
. 这将使您的输入(
type
)与字符文字 'p'
和'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.) (顺便说一句,如果这让老师感到难过,我担心他们教Java的程度是多么合适。这是相当基本的东西。)
你不能在case语句中使用变量,它必须是文字字符(例如'p'
, 'f'
)。
In case statement 在案例陈述中
You should use a (character switch) or a (number switch) only 您应该只使用(字符开关)或(数字开关)
For example 例如
You can use a (character switch) 你可以使用(字符开关)
switch (type) {
case 'p':
.......
case 'f':
......
}
NOT 不
switch (type) {
case p:
.......
case f:
......
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.