从用户输入打印两个最高值

时间:2016-09-09 16:27:45

标签: java for-loop compare

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

<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2014 The Android Open Source Project

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->

<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/text_select_handle_middle_mtrl_alpha"
android:tint="?attr/colorControlActivated" />

4 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

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

int biggest = num1 > 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

答案 3 :(得分:0)

  

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

一些事情:

  • 关闭扫描程序(以及与IO相关的资源)的良好做法

  • 减少if语句阻止膨胀以便于阅读

  • 指定2个保证数字,因此请在循环

  • 之前尝试解析这些数字
  • 可以删除system.exit调用或替换system.exit并将大量代码移回到较大的if-else块中,如OP中的原始状态(但我回想起可读性)

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

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

    进行指定
    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);
    }
    

    }