我有两个类用于计算 ISP 计划的成本并收集输入/显示成本。 ISPMain.java 和ISP.java ISPMain 应该显示服务计划并要求用户通过包的字母选择他们的计划,例如包a、包b 或包c。我已将其设置为用户输入字符来选择计划。如果计划不是套餐 c(无限制计划),系统会提示用户输入他们使用的时间。
一旦输入小时数并将其存储在hoursUsed 中,ISP.java 就会计算成本,然后ISPMain.java 将其显示出来。我的问题是我在 ISP 中的 switch 语句仅显示默认值,我不知道为什么。谁能解释一下吗?
public class ISPMain
{
public static void main(String[] args)
{
char pkg;
double hoursUsed;
Scanner kb = new Scanner(System.in);
System.out.println("The three packages offered are: ");
System.out.println("Package A: For $9.95 per month, 10 hours of access are provided. \nAdditional hours are $2.00 per hour.");
System.out.println("Package B: For $14.95 per month, 20 hours of access are provided. \nAdditional hours are $1.00 per hour.");
System.out.println("Package C: For $19.95 per month, unlimited access is provided.");
System.out.println("Please type the letter of the package you have: ");
pkg = kb.nextLine().toUpperCase().charAt(0);
if(pkg == 'A')
{
System.out.print("Enter number of hours: ");
hoursUsed = kb.nextDouble();
}
else if(pkg == 'B')
{
System.out.print("Enter number of hours: ");
hoursUsed = kb.nextDouble();
}
else if(pkg == 'C')
{
System.out.print("You have unlimited access! No need to enter hours used. \n");
}
ISP user = new ISP();
System.out.print("Total charges: " + user.calculateCharges());
}
}
ISP.java 中的 switch 语句:
public double calculateCharges()
{
switch (pkg)
{
case 'A':
if (hoursUsed < 10)
{
return 9.95;
}
else
{
return (hoursUsed - 10)*2 + 9.95;
}
case 'B':
if (hoursUsed < 20)
{
return 14.95;
}
else
{
return (hoursUsed - 20) + 14.95;
}
case 'C':
return 19.95;
default:
System.out.println("Invalid input!");
return 0;
}
}
总而言之,我的 if else 工作正常,但开关仅显示“无效输入”
最佳答案
正如其他人所说,您需要将 pkg 变量放入 switch 语句的范围内。试试这个:
public double calculateCharges(char pkg){
switch(pkg){
case('A'):{
//insert code here
break;
}
case('B'):{
//insert code here
break;
}
case('C'):{
//insert more code here
break;
}
default:{
//code here
break;
}
}
}
然后调用您的方法,如下所示:
System.out.print("Total charges: " + user.calculateCharges(pkg));
关于Java switch 语句无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42910445/