我有两个类来计算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));