有一个java代码输出错误

时间:2016-06-11 00:37:35

标签: java

import java.util.Scanner;

public  class StrictDescending
{
    public static void main( String[] args )
    {
        final int SENTINEL = 1000;
        Scanner n = new Scanner(System.in);
        int prev = n.nextInt();

        if (prev >= SENTINEL)
        {
            System.out.println("Empty list");
            return;
        }
        while (true) 
        {
            int next = n.nextInt();
            if (next >= SENTINEL) {
                break;
            } else if (next >= prev) {
                System.out.println("No, the list is not in descending order.");
            }
            prev = next;
        }
        System.out.println("Yes, the list in in descending order.");
    }
}

我正在尝试运行这个程序,并查看3位整数的列表,当下面的3位数整数没有下降时,我想要打印没有列表不下降,如果列表正在降序,它来了到非3位数字如1000我想打印是列表下降我的输出工作,但当我放入一个非降序的整数列表,它吐出两个输出语句

此输入

150 140 140 120 1000

我得到了

No, the list is not in descending order.

No, the list is not in descending order.

Yes, the list in in descending order.

当我想要

No, the list is not in descending order.

1 个答案:

答案 0 :(得分:0)

如果我已正确理解您的问题描述,您可以通过设置标志来解决它,并将其用作条件来打印“是,列表按降序排列”。或者“不,列表不按降序排列。”

import java.util.Scanner;

public class StrictDescending {

    public static void main(String[] args) {
        final int SENTINEL = 1000;
        Scanner n = new Scanner(System.in);
        int prev = n.nextInt();

        if (prev >= SENTINEL) {
            System.out.println("Empty list");
            return;
        }
        boolean descending = true;
        while (true) {
            int next = n.nextInt();
            if (next >= SENTINEL) {
                break;
            } else if (next >= prev) {
                descending = false;
            }
            prev = next;
        }
        if (descending) {
            System.out.println("Yes, the list is in descending order.");
        } else {
            System.out.println("No, the list is not in descending order.");
        }
    }
}