首页 > 解决方案 > 为什么我的代码没有返回 N 的最大值?

问题描述

输出是一个巨大的数字。我已经尝试了大约 10 种不同的代码变体。我知道最大的问题是我没有正确理解。我正在尝试自学。这个问题让我完全难住了。任何帮助,将不胜感激。

package com.codegym.task.task05.task0532;
import static java.lang.Integer.*;
import java.io.*;

/* 
Task about algorithms
Write a program that:
1. reads a number N (must be greater than 0) from the console
2. reads N numbers from the console
3. Displays the maximum of the N entered numbers.


Requirements:
1. The program should read the numbers from the keyboard.
2. The program must display a number on the screen.
3. The class must have a public static void main method.
4. Don't add new methods to the Solution class.
5. The program should display the maximum of the N entered numbers.
6. The program should not display anything if N is less than or equal to 0.
*/

public class Solution {
    public static void main(String[] args) throws Exception {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        int maximum = MAX_VALUE;
        int N = Integer.parseInt(reader.readLine());


        int i;
        int N2 = 0 ;
        for (i = 0; i != N; i++){
            N2 = Integer.parseInt(reader.readLine());
            maximum = N2;

        }
        System.out.println(maximum);

    }
}

标签: javamax

解决方案


您的逻辑不正确,并在每次迭代时覆盖最大值而不实际检查该值。您想要的逻辑是从MIN_VALUEof开始Integer,并为每个传入值分配一个新的最大值,如果它大于先前的最大值。

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int maximum = MIN_VALUE;
int N = Integer.parseInt(reader.readLine());

for (int i=0; i < N; i++){
    int N2 = Integer.parseInt(reader.readLine());
    if (N2 > maximum) {
        maximum = N2;
    }
}
System.out.println(maximum);

注意:这里有一个微妙但不太可能的边缘情况。如果用户输入输入N = 0的数量,则报告的最大值将为Integer.MIN_VALUE. 这有点毫无意义,但是是上面使用的逻辑的产物。


推荐阅读