java - 为什么我的代码没有返回 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);
}
}
解决方案
您的逻辑不正确,并在每次迭代时覆盖最大值而不实际检查该值。您想要的逻辑是从MIN_VALUE
of开始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
. 这有点毫无意义,但是是上面使用的逻辑的产物。
推荐阅读
- javascript - x 选项在 y 位置的排列
- javascript - 如何让 go-ipfs 使用 ws-star 进行 punsub
- python - 无法证明python中的输出
- mysql - mysql中返回的行数不同
- python - 写入csv时如何指定分隔符是换行符?蟒蛇硒
- javascript - 奇怪的 javascript 表示法 - 这是什么意思?
- javascript - React .play() 错误未捕获(承诺中)
- python - Pandas 中的字符串替换
- android-studio - 打开文件夹作为 android studio 项目
- html - 我有一个带有图像和按钮的 div。按钮居中,但图像不居中,随页面宽度而变化