【问题标题】:Printing the two highest values from user input打印来自用户输入的两个最高值
【发布时间】:2016-09-09 16:27:44
【问题描述】:

我有一个任务,我必须编写一个代码,让用户决定要写入的 int 值的数量,然后决定这些值应该是什么。用户必须至少有 2 个输入。然后程序将比较输入的值,然后打印出两个最高值。到目前为止,我设法打印出最高值,但我不确定我这样做的方式有什么问题,因为如果我选择打印出 2 个数字并且首先输入最高的数字,输出只会变为 0。而且我也不确定如何跟踪第二高的数字。不胜感激。

import java.util.Scanner;
public class ToStoersteTall{
    public static void main(String[] args){
        System.out.println("How many numbers? (minimum 2)?:");
        Scanner reader = new Scanner(System.in);

        if (reader.hasNextInt()) {
            int numbers = reader.nextInt();
            if (numbers >= 2) {
                System.out.println("Enter value #1");
                if (reader.hasNextInt()) {
                    int num1 = reader.nextInt();
                    System.out.println("Enter value #2");
                    if (reader.hasNextInt()) {
                        int num2 = reader.nextInt();

                        int biggest = 0;
                        for (int i = 3; i <= tall; i++) {
                            System.out.println("Enter value #" + i);
                            int num3 = reader.nextInt();
                            biggest = num1;
                            if(biggest < num3){
                                biggest = num3;
                            }
                        }
                        System.out.println(biggest);
                    } else {
                        System.out.println("Please enter an integer");
                    }                   
                } else {
                    System.out.println("Please enter an integer");
                }
            } else {
                System.out.println("Please enter an integer equal or higher than 2.");
            }   
        } else {
            System.out.print("Vennligst oppgi et heltall større eller lik 2.");
        }   
    }
}

【问题讨论】:

  • 代码for循环中tall的值是多少?
  • tall 声明在哪里?
  • 抱歉,tall 应该是数字。我最初用挪威文本和变量名编写代码,所以那里可能是挪威文本,我忘记翻译了

标签: java for-loop compare


【解决方案1】:

您已经在跟踪最大的,那么为什么不跟踪第二大呢?解决此问题的另一种简单方法是将所有数字保留在一个列表中,按数字大小对列表进行排序,然后获取两个最高的条目。

【讨论】:

    【解决方案2】:

    我尝试了您的代码并使用数组来解决问题。

    import java.util.Scanner;
    
    public class Main {
        static int secondHighest(int... nums) {
            int high1 = Integer.MIN_VALUE;
            int high2 = Integer.MIN_VALUE;
            for (int num : nums) {
                if (num > high1) {
                    high2 = high1;
                    high1 = num;
                } else if (num > high2) {
                    high2 = num;
                }
            }
            return high2;
        }
        public static void main(String[] args) {
            System.out.println("How many numbers? (minimum 2)?:");
            Scanner reader = new Scanner(System.in);
            if (reader.hasNextInt()) {
                int numbers = reader.nextInt();
                int[] array = new int[numbers];
                if (numbers >= 2) {
                    System.out.println("Enter value #1");
                    if (reader.hasNextInt()) {
                        int num1 = reader.nextInt();
                        array[0] = num1;
                        System.out.println("Enter value #2");
                        if (reader.hasNextInt()) {
                            int num2 = reader.nextInt();
                            array[1] = num2;
                            int biggest = 0;
                            for (int i = 3; i <= numbers; i++) {
                                System.out.println("Enter value #" + i);
                                int num3 = reader.nextInt();
                                array[i-1] = num3;
                            }
                            System.out.println("second largest number is" + secondHighest(array));
                            int largest = 0;
                            for(int i =0;i<array.length;i++) {
                                if(array[i] > largest) {
                                    largest = array[i];
                                }
                            }
    
                            System.out.println("Largest number in array is : " +largest);
    
                        } else {
                            System.out.println("Please enter an integer");
                        }
    
                    } else {
                        System.out.println("Please enter an integer");
                    }
                } else {
                    System.out.println("Please enter an integer equal or higher than 2.");
                }
            } else {
                System.out.print("Vennligst oppgi et heltall større eller lik 2.");
            }
        }
    }
    

    测试

    How many numbers? (minimum 2)?:
    6
    Enter value #1
    3
    Enter value #2
    4
    Enter value #3
    5
    Enter value #4
    6
    Enter value #5
    7
    Enter value #6
    8
    second largest number is7
    Largest number in array is : 8
    

    【讨论】:

      【解决方案3】:

      我有一个任务,我必须编写一个代码,让用户决定要写入的 int 值的数量,然后决定这些值应该是什么。用户必须至少有 2 个输入。然后程序将比较输入中的值,然后打印出两个最高值。到目前为止,我设法打印出最高值,但我不确定我这样做的方式有什么问题,因为如果我选择打印出 2 个数字并且首先输入最高的数字,输出只会变为 0。而且我也不确定如何跟踪第二高的数字。不胜感激。

      几件事:

      • 关闭扫描器(以及一般的 IO 相关资源)的良好做法

      • 减少了 if 语句块膨胀以提高可读性

      • 您指定了 2 个保证数字,因此尝试在循环之前解析这些数字

      • 可以删除 system.exit 调用或替换 system.exit 并将大量代码移回较大的 if-else 块中,就像 OP 中的原始状态一样(但为了便于阅读,我会重新引用)

      • 添加了对输入的第一个和第二个数字的检查,以确保 high1 是最高值,high2 是第二高值。

      • 在循环和检查值时保持顺序(注意:不使用数组),如果数字是新高,则替换 high1 并将 high1 的值向下移动到 high2,或者如果数字是第二(新)高,则替换高2。如果值相等,则排除此逻辑,您可能需要根据自己的约束来指定

        import java.io.IOException;
        import java.util.Scanner;
        public class ToStoersteTall {
            public static void main(String[] args) throws IOException {
            System.out.println("How many numbers? (minimum 2)?:");
            Scanner reader = new Scanner(System.in);
            int n = 0;
            if (reader.hasNextInt()) {
                n = reader.nextInt();
            } else {
                System.out.println("Vennligst oppgi et heltall større eller lik 2.");
                System.exit(-1); // quits execution
            }
        
            if (n < 2) {
                System.out.println("Please enter an integer equal or higher than 2.");
                System.exit(-2);
            }
        
            // Since guaranteed 2 numbers, parse and assign now
            int high1 = 0, high2 = 0;
            System.out.println("Enter value # 1");
            if (reader.hasNextInt())
                high1 = reader.nextInt();
            System.out.println("Enter value # 2");
            if (reader.hasNextInt())
                high2 = reader.nextInt();
        
            // check to see if a switch to keep correct highest order, swap values if so
            if (high1 < high2) {
                int t = high2;
                high2 = high1;
                high1 = t;
            }
        
            // loop won't execute if only 2 numbers input, but will if 3 or more specified at start
            for (int i = 2; i < n; ++i) {
                System.out.println("Enter value #" + (i + 1));
                if (reader.hasNextInt()) {
                    int t = reader.nextInt();
                    if (t > high1) {
                        high2 = high1; // throw away high2 value and replace with high1
                        high1 = t; // replace high1 value with new highest value                    
                    } else if (t > high2) {
                        high2 = t;
                    }
                } else {
                    System.out.println("Please enter an interger");
                }
            }
        
            reader.close();
        
            System.out.println("The two highest numbers are: " + high1 + ", " + high2);
        }
        

        }

      【讨论】:

      • 如果输入 1
      • 很高兴我能帮上忙。 IOException 导入也是由于我添加了 reader.close();在 main() 方法末尾附近的方法调用。如果您还没有了解异常,您可以简单地删除 reader.close() 方法调用,删除 main method() 签名的“throws IOException”部分,并删除“import java.io.IOException”行.
      【解决方案4】:

      您的程序中存在逻辑错误。如果numbers 为2,则for 循环永远不会执行,biggest 的值保持为零,因为它永远不会更新。更改您的最大声明以反映目前找到的最大值。

      int biggest = num1 &gt; num2 ? num1 : num2;

      这样,如果 for 循环永远不会执行,那么最大的将是前两个数字的最大值。

      至于跟踪第二高的值,您可以引入另一个变量secondBiggest,以与biggest 类似的方式初始化,然后在 for 循环中编写逻辑来更新此值。但是,在我看来,更改策略以将输入的值保存到数组中会容易得多,然后在输入所有输入后,从数组中计算您想要的任何值。这将导致 IMO 更清洁的解决方案。

      (我假设 for 循环中的 tall 实际上是 numbers...)

      import java.util.Scanner;
      
      public class Foo{
      
          public static void main(String[] args){
      
              System.out.println("How many numbers? (minimum 2)?:");
          Scanner reader = new Scanner(System.in);
      
              if(reader.hasNextInt()){
      
                  int numbers = reader.nextInt();
                  if(numbers >= 2){
      
                  int[] list = new int[numbers];
      
                      for(int i = 0; i < numbers; i++){
                          System.out.println("Enter value #" + (i + 1));
                          if(reader.hasNextInt())
                              list[i] = reader.nextInt();
                      }//for
      
                      int biggest = 0;
                      int secondBiggest = 0;
      
                      // find the values you want
                      for(int i = 0; i < numbers; i++){
                          if(list[i] > biggest){
                              secondBiggest = biggest;
                              biggest = list[i];
                          }//if
                          else if(list[i] > secondBiggest)
                            secondBiggest = list[i];
                      }//for
      
                      // print your results
                      System.out.println("The biggest integer is: " + biggest);
                      System.out.println("The second biggest integer is: " + secondBiggest);
      
                  }//if
              }//if
          }//main
      }//class
      

      【讨论】:

        猜你喜欢
        • 2022-06-12
        • 2015-12-30
        • 2016-11-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-08
        • 2018-01-29
        • 1970-01-01
        相关资源
        最近更新 更多