【问题标题】:for loop condition and if statmentfor 循环条件和 if 语句
【发布时间】:2014-11-26 17:03:25
【问题描述】:

我创建了一个 for 循环,我希望当用户输入负值并给出消息时循环中断。我不希望程序计算负值。

public class test1
{
    public static void main(String[] args)
    {
        PrintStream output = new PrintStream(System.out);
        Scanner input = new Scanner(System.in);
        List<Integer> yolo = new ArrayList<Integer>();
        double sum = 0;
        output.println("Enter your integers\n" + "(Negative=sentinel)");

        // add the values to your empty Array except the negative entries
        for (int entry = input.nextInt(); entry < 0 ; entry = input.nextInt())
        {
            yolo.add(entry);
            if (entry >= 0 )
            {
                sum += entry;
            }
            else {
                output.println("Your list is empty");
            }
        }

我尝试使用 Outerloop:, 和 break outerloop;但即使是正整数,它也会打破循环。

【问题讨论】:

    标签: java list if-statement for-loop break


    【解决方案1】:

    改成

    for ( int entry = input.nextInt(); entry >= 0; entry = input.nextInt())
    

    因为当前循环仅在输入的数字为

    所以循环具有语义(意义):

    run while the entries are >= 0, read every time from the input to entry
    

    当用户输入负数时,循环结束。

    【讨论】:

    • 循环有效,但是当我输入负值时,它并没有给出我想要的按摩〜。〜
    • 你可以简单地在循环之后添加system.out.println。
    【解决方案2】:
    // add the values to your empty Array except the negative entries
    

    看来您还错过了一件小事。 你想做的是:

    if (entry >= 0){
      yolo.add(entry);
      sum += entry;
    }
    

    对于您的问题,我认为您声明的 for 循环是错误的,因为每次调用 input.nextInt() 时,它都会要求新的输入,并且无论发生什么情况,您都可以第二次输入负值。

    【讨论】:

      猜你喜欢
      • 2022-11-26
      • 2013-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-22
      • 1970-01-01
      • 1970-01-01
      • 2019-05-02
      相关资源
      最近更新 更多