解释看你的代码是如何工作的,最明智的地方,打破可能是输入产品名称后。这意味着你不能存储停止产品...我已经把它作为大写(如果你不关心案例,你可以使用equalsIgnoreCase)。
事情是这样的:
for(int i=0; i<=numberOfItems; i++)
{
System.out.println("Enter product name (or STOP to stop)");
String tmpProduct = input.nextLine();
//trim to avoid whitespace
if ("STOP".equals(tmpProduct.trim())) {
break; //we stop the loop here
}
//they didn't type STOP, guess they wanted a product.
productName[i]=tmpProduct;
System.out.println("Enter price of product");
productPrice[i]=input.nextDouble();
System.out.printf("%s,%n,%.2f",productName[i],productPrice[i]);
}
这也避免了外循环的需要。如果你想问问每件产品(这可能会在一段时间后变得烦人),那么你可以在请求双倍数的情况下进行检查并提示。无论你想
for(int i=0; i<=numberOfItems; i++)
{
System.out.println("Enter product name");
//they didn't type STOP, guess they wanted a product.
productName[i]=input.nextLine();
System.out.println("Enter price of product");
productPrice[i]=input.nextDouble();
System.out.printf("%s,%n,%.2f",productName[i],productPrice[i]);
System.out.println("type STOP to stop or anything else to continue");
String tmp = input.nextLine();
//trim to avoid whitespace problems
if ("STOP".equals(tmp.trim())) {
break; //we stop the loop here
}
}
使用'break'来循环出来。 – yogidilip
你需要break语句吗? https://www.tutorialspoint.com/java/java_break_statement.htm – user3685285
你有两个循环,你想停止哪一个循环? – Adam