如果在switch语句中匹配大小写,我需要发出break while循环。案例如下:如果用户输入的数字小于零或大于五。除了我提到的两个例外,我的开关工作大部分都是我的。这是我的代码:
import java.util.Scanner;
public class Product
{
public static void main(String args[])
{
int cntr = 0;
int product = 0;
int units = 0;
double totalcost = 0;
Scanner MK = new Scanner(System.in);
cntr=0;
while (cntr >= 0 && cntr <=5)
{
System.out.println("Enter Product no.(1-5) or -1 to Quit");
product = MK.nextInt();
switch(product) {
case 1:
{
System.out.println("Product " + (cntr+1));
System.out.println("Enter Quantity or -1 to Quit");
product = MK.nextInt();
double cost = 2.98;
totalcost = totalcost + cost*product;
System.out.println("Current total cost: " + totalcost);
cntr++;
}
break;
case 2:
{
System.out.println("Product " + (cntr+1));
System.out.println("Enter Quantity or -1 to Quit");
product = MK.nextInt();
double cost = 4.50;
totalcost = totalcost + cost*product;
System.out.println("Current total cost: " + totalcost);
cntr++;
}
break;
case 3:
{
System.out.println("Product " + (cntr+1));
System.out.println("Enter Quantity or -1 to Quit");
product = MK.nextInt();
double cost = 9.98;
totalcost = totalcost + cost*product;
System.out.println("Current total cost: " + totalcost);
cntr++;
}
break;
case 4:
{
System.out.println("Product " + (cntr+1));
System.out.println("Enter Quantity or -1 to Quit");
product = MK.nextInt();
double cost = 4.49;
totalcost = totalcost + cost*product;
System.out.println("Current total cost: " + totalcost);
cntr++;
}
break;
case 5:
{
System.out.println("Product " + (cntr+1));
System.out.println("Enter Quantity or -1 to Quit");
product = MK.nextInt();
double cost = 6.87;
totalcost = totalcost + (cost*product);
System.out.println("Current total cost: " + totalcost);
cntr++;
}
case 6:
{
System.out.println("Product " + (cntr+1));
System.out.println("Enter Quantity or -1 to Quit");
//product = MK.nextInt();
//double cost = 2.98;
//totalcost = totalcost + cost*product;
System.out.println("Current total cost: " + totalcost);
//cntr++;
}
break;
}
System.out.println("Total cost-->" +totalcost);
}
}
}
如果任何人可以指出如何在输入小于零或大于5的程序时停止我的程序,我会非常感激。
答案 0 :(得分:4)
有两种选择:
使用您希望循环结束时设置的标记(在default
或-1
子句中)或
在default
(或-1
)条款中使用labelled statement和定向 break
在特定的情况下,您说您希望整个程序结束,您可以使用System.exit
以下是关于选项2的更多信息:
label: while (...) { // <== Labelled statement
switch (...) {
case ...:
// ...
break; // <=== Normal (undirected) break, just exits what
// it's in (switch in this case)
// ...
default:
break label; // <=== Directed break, exits loop
}
}
它对于嵌套循环也很方便。
旁注:您{
条款中的陈述不需要}
和case
。 case
的代码一直持续到break
。 (是的,它与其他陈述有点不同。)
附注2:您在提示中说过Enter Product no.(1-5) or -1 to Quit
,但您有1
到 6
(含)的值。你可能意味着Enter Product no.(1-**6**) or -1 to Quit
。