Почему мой код не возвращает максимальное значение N? - PullRequest
0 голосов
/ 21 января 2020

На выходе получается огромное количество. Я пробовал около 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);

    }
}

Ответы [ 3 ]

1 голос
/ 21 января 2020

Ваш лог c неверен и перезаписывает максимум на каждой итерации без фактической проверки значения. Логика c, которую вы хотите, должна начинаться с MIN_VALUE из 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. Это несколько бессмысленно, но является артефактом логики c, используемой выше.

0 голосов
/ 21 января 2020

Значение, присвоенное maximum, перезаписывается каждым новым входным значением, анализируемым считывателем на каждой итерации:

int i;
int N2 = 0 ;
for (i = 0; i != N; i++){
    N2 = Integer.parseInt(reader.readLine());
    maximum = N2; // overwrites maximum with the newly parsed int

}

Вам нужен способ отслеживать максимальное число на каждом итерация по сравнению с последним известным максимумом; начиная с минимального значения целого числа в качестве максимального.

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 N = Integer.parseInt(reader.readLine());
        if (N < 1) {
            return; // covers requirement 6. The program should not display anything if N is less than or equal to 0.
        }


        int maximum = MIN_VALUE; // start off with the min value of integer as max value
        int i;
        int N2;
        for (i = 0; i < N; i++){
            N2 = Integer.parseInt(reader.readLine());
            maximum = Math.max(N2, maximum);

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

0 голосов
/ 21 января 2020

Почему бы вам не попробовать это?

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 = Integer.MIN_VALUE;
        int N = Integer.parseInt(reader.readLine());


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

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

Идея состоит в том, чтобы изначально установить значение максимума как очень маленькое значение, чтобы мы могли сравнить и получить Наибольшее значение из набора значений. На каждой итерации новое число считывается и сравнивается с существующим значением максимума. Если оно выше maximum, оно заменяет максимальное. Вот что я пробовал в качестве входных данных

5
4
8
9
1
2

Output

9

5 - это число целых чисел, которые мы вводим, поэтому сначала давайте предположим, что очень небольшое значение для maximum (-2134 ). Когда он видит первое значение (4), сравнивает его с текущим максимумом (4> -2134), он присваивает значение maximum как 4. Итерация продолжается, и максимальное значение равно 9, при сравнении со значениями 1 и 2, значение максимума остается неизменным. Надеюсь, это поможет!

...