按降序排列的Java代码

时间:2016-06-10 20:07:06

标签: java

import java.util.Scanner ;

public class StrictDescending {

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

    if (firstValue <1000)
    {

        int secondValue = firstValue ;
        secondValue = in.nextInt() ;
        while(secondValue < firstValue)
        {
            if(firstValue > secondValue)
            {
                System.out.println("Yes, the list is in descending order.") ;
            }
            else 
            {
                System.out.println("No, the list is not in descending order.") ;
            }
            secondValue = in.nextInt();
        }    
    }
}
  

给定三位数整数列表,确保列表中的数字严格按降序排列。程序的输出应为“是,列表按降序排列。”或“否,列表不按降序排列。”如果列表中的数字发生故障,那么您的程序应该停止在那一点上并生成输出“否,数字不是按降序排列。”相等的连续数字不应按降序排列

输入:

150
130
120
1000

我的代码输出

Yes, the list is in descending order.
Yes, the list is in descending order. 

3 个答案:

答案 0 :(得分:1)

如果您发现两个号码无序,则可以立即声明列表不按降序排列。相反的情况并非如此:如果你发现两个数字,你就不知道整个列表是否有序。

您的程序在读完前两个数字后立即打印出决定。您需要延迟&#34;是,列表按降序排列。&#34;打印输出,直到您检查了所有数字。

答案 1 :(得分:1)

这看起来很像一个家庭作业问题,这意味着我有点犹豫要回答它。所以,我不打算提供任何代码,但我会建议一种方法:

  1. 读入第一个号码,商店为previousValue
  2. 如果您有更多号码,请将其加载为currentValue
  3. 如果currentValue大于previousValue,请停止。答案是否定的。
  4. 否则,将previousValue设置为currentValue并继续循环。
  5. 如果到达循环结束(即你到达你的哨兵),而你还没有停下来并退出,那么你就知道答案是肯定的。
  6. 或者,换句话说:寻找任何大于之前的数字。如果找到一个,则列表不按降序排列。如果你没有找到一个你的数字用完了,那就是。

答案 2 :(得分:0)

问题在于你的逻辑。输入1000后,您的代码将检查您的while语句中的表达式,因为它130&gt; 1000评估为false它退出而不打印&#34; No&#34;言。

此代码将产生所需的结果。

int secondValue;
            do {
                secondValue = in.nextInt();
                if (firstValue > secondValue) {
                    System.out.println("Yes, the list is in descending order.");
                } else {
                    System.out.println("No, the list is not in descending order.");
                }
            } while (secondValue < firstValue);
相关问题