[英]How to make the switch statement more accurate?
我们被要求使用switch语句编写一个程序。
这是我的代码:
double price = 0, totalPrice;
System.out.print("Enter the number of your choice: ");
int optionNumber = Integer.parseInt(kb.readLine());
switch(optionNumber)
{
case 1:
price = 190.00;
break;
case 2:
price = 410.00;
break;
default:
System.out.println("ERROR: Invalid number!");
break;
}
System.out.print("Enter quantity: ");
int quantity = Integer.parseInt(kb.readLine());
totalPrice = price * quantity;
因此,基本上,用户将输入一定的数字,并且价格会有所不同...在switch语句内。 但是,如果用户输入了错误的数字,它将显示一条错误消息,并且我不希望用户输入将在switch语句之后执行的数量。 我们不允许使用任何方法或函数,我也不想这样重复编码:
System.out.print("Enter the number of your choice: ");
int optionNumber = Integer.parseInt(kb.readLine());
switch(optionNumber)
{
case 1:
price = 190.00;
System.out.print("Enter quantity: ");
int quantity = Integer.parseInt(kb.readLine());
totalPrice = price * quantity;
System.out.print("Total price: " + totalPrice);
break;
case 2:
price = 410.00;
System.out.print("Enter quantity: ");
int quantity = Integer.parseInt(kb.readLine());
totalPrice = price * quantity;
System.out.print("Total price: " + totalPrice);
break;
default:
System.out.println("ERROR: Invalid number!");
break;
}
如果还有其他方法,方法,函数或代码反复使用,还有其他方法可以不使用吗? 任何帮助将不胜感激。
用作:
while(!valid option)
//do this stuff
如果输入的数字有效,请使用标志并将其设置为true,因此它将转到您的下一条指令; 否则再次要求输入。
如果选择了无效选项,则可以使用布尔标志并将其设置为false。
然后仅进一步询问用户flag是否为true。
System.out.print("Enter the number of your choice: ");
int optionNumber = Integer.parseInt(kb.readLine());
boolean flag = true;
switch (optionNumber) {
case 1:
price = 190.00;
break;
case 2:
price = 410.00;
break;
default:
flag = false;
System.out.println("ERROR: Invalid number!");
break;
}
if (flag) {
System.out.print("Enter quantity: ");
int quantity = Integer.parseInt(kb.readLine());
totalPrice = price * quantity;
System.out.print("Total price: " + totalPrice);
}
你可以只删除default
从switch
语句和检查,看看,如果价格等于0后switch
语句
double price = 0, totalPrice;
System.out.print("Enter the number of your choice: ");
int optionNumber = Integer.parseInt(kb.readLine());
switch(optionNumber)
{
case 1:
price = 190.00;
break;
case 2:
price = 410.00;
break;
}
if (price == 0)
{
System.out.println("ERROR: Invalid number!");
}
else
{
System.out.print("Enter quantity: ");
int quantity = Integer.parseInt(kb.readLine());
totalPrice = price * quantity;
System.out.print("Total price: " + totalPrice);
}
当已有一个( price
)可以检查的默认值0
,这可以防止您添加不必要的变量(如布尔标志)。
引发异常
default:
throw new InvalidArgumentException("Invalid number!");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.