作为关键字来停止for循环

作为关键字来停止for循环

本文介绍了我如何使用“停止”作为关键字来停止for循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 numberOfItems设置为一个大数字,但想在中途停止循环。我需要一段时间的帮助。请不要ArrayList,我还不熟悉。

I want to set "numberOfItems" as a large number but want to stop the loop midway. I need help for the while part. No ArrayList please, I'm not familiar with that yet.

do
 {
    for(int i=0; i<=numberOfItems; i++)
    {
       System.out.println("Enter product name");
       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]);
    }
 }
 while (! (productName[i]= input.nextLine("stop")));


推荐答案

查看代码的工作方式,最明智折断的地方可能是在输入产品名称之后。这意味着您无法存储STOP产品...我将其保留为大写(您可以使用(如果您不关心大小写)。

Looking at how your code is working, the most sensible place to break is probably after entering a product name. This would mean you can't store a STOP product... I've left this as UPPERCASE (you can use equalsIgnoreCase if you don't care about case).

是这样的:

    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]);
    }

这也避免了外部的需要循环。如果您想问问每种产品之后(一段时间后可能会很烦),则可以在请求双精度后放支票并提示。

This also avoids the need for the outer loop. If you would rather ask after every product (this could get annoying after a while) then you can put the check and prompt after requesting the double.

    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
       }
    }

这篇关于我如何使用“停止”作为关键字来停止for循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 13:44