[英]Java switch statement: Constant expression required, but it IS constant
[英]Constant expression required? (Java switch statement)
我不知道是什么導致了這個錯誤。 我的老師和我老去了,找不到什么問題。
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);
}
}
它在編譯時拋出一個“需要常量表達式”錯誤並指向case p:line,但是,它也會拋出f:如果我切換它們,那么我必須完全關閉它。
是的, case
表達式必須是常量(或枚舉常量名稱) - 你不能使用變量。 有關更多詳細信息,請參閱Java語言規范部分14.11(switch語句) 。 (你甚至沒有初始化變量,所以不清楚你預期會發生什么,說實話。)
你的意思是:
case 'p':
...
case 'f':
...
? 這將使您的輸入( type
)與字符文字 'p'
和'f'
匹配。
(順便說一句,如果這讓老師感到難過,我擔心他們教Java的程度是多么合適。這是相當基本的東西。)
你不能在case語句中使用變量,它必須是文字字符(例如'p'
, 'f'
)。
在案例陳述中
您應該只使用(字符開關)或(數字開關)
例如
你可以使用(字符開關)
switch (type) {
case 'p':
.......
case 'f':
......
}
不
switch (type) {
case p:
.......
case f:
......
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.