java 如何使用扫描仪和 for 循环(无数组)查找第二大数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1975669/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 18:47:01  来源:igfitidea点击:

How to find second largest number using Scanner and for loop(no array)

javaalgorithmjava.util.scanner

提问by landscape

So I can easily accomplish task to find largest number and then if can be divided by three, print out. But do not know how to find second largest number from users sequence. Thanks for any hints!

所以我可以轻松地完成查找最大数的任务,然后如果可以除以三,则打印出来。但是不知道如何从用户序列中找到第二大数字。感谢您的任何提示!

public class SecondLargest {

    public static void main(String[] args) {
        int max = 0;
        Scanner scan = new Scanner(System.in);
        System.out.println("How many numbers?");
        int n = scan.nextInt();

        System.out.println ("Write numbers: ");
        for(int i=0; i<n; i++){
            int c = scan.nextInt();
            if(c>=max && c%3 == 0){
                max = c;
                }
            else
                System.out.println("There is no such number.");



        }
        System.out.println(max);
    }
}

回答by Bozho

int secondLargest = 0;
.....
for (..) {
   ....
   if (c % 3 == 0) {
       if (c >= max) {
           secondLargest = max;
           max = c;
       }
       if (c >= secondLargest && c < max) {
           secondLargest = c;
       }
   }
   ....
}

回答by Drakosha

You just need to keep 2 variables, one for maximum and another for second_maximum and update them appropriately.

您只需要保留 2 个变量,一个用于最大值,另一个用于 second_maximum 并适当更新它们。

For a more general approach, take a look at selection algorithms

对于更通用的方法,请查看选择算法

回答by Jay Shah

Below code will work

import java.util.Scanner;

public class Practical4 {
    public static void main(String a[]) {
        int max = 0, second_max = 0, temp, numbers;
        Scanner scanner = new Scanner(System.in);
        System.out.println("How many numbers do you want to enter?");
        numbers = scanner.nextInt();
        System.out.println("Enter numbers:");
        for (int i = 0; i < numbers; i++) {
            if (i == 0) {
                max = scanner.nextInt();
            } else {
                temp = scanner.nextInt();
                if (temp > max) {
                    second_max = max;
                    max = temp;
                }
                else if(temp>second_max)
                {
                 second_max=temp;
                }
            }
        }
        scanner.close();
        System.out.println("Second max number is :" + second_max);
    }
}