P
P
PRAIT2019-06-07 12:48:50
Java
PRAIT, 2019-06-07 12:48:50

How to write a program that counts 4 numbers from the keyboard and displays the largest of them?

Actually a subject.
You need to write a program that counts 4 numbers from the keyboard and displays the largest of them. I don't quite understand how to do it.
I have code

package code;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        try (Scanner input = new Scanner(System.in)) {
            int a;
            int b;
            int c;
            int max;
            System.out.println("Iput A");
            a = input.nextInt();
            System.out.println("Iput B");
            b = input.nextInt();
            System.out.println("Iput C");
            c = input.nextInt();

            max = a;
            if (b > max) {
                max = b;
            }
            if (c > max) {
                max = c;
            }

            System.out.println("Max = " + max);
        }
    }
}

Here, in general, everything is very clear, but there is a task in which you need to make a SUBJECT. As I understand it, you need to limit the input of numbers from 4 numbers, if the entered number is less than 4 or more than 4 numbers, a warning will be displayed to the user that 4 numbers must be entered. Thank you all very much for your help.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
T
Timofey Fedyanin, 2019-06-07
@Tim06ka

Here is my version in one statement

IntStream.range(0, 4)
                 .mapToObj(i -> System.in)
                 .map(Scanner::new)
                 .map(Scanner::nextInt)
                 .reduce(Integer::max)
                .ifPresent(System.out::println);

R
Ronald McDonald, 2019-06-07
@Zoominger

Make a loop from 0 to 3 and stick the reading into an array and sort it in descending order. The first number is the maximum.

R
Roman, 2019-06-07
@myjcom

public static void main(String[] args) 
{
  Scanner io = new Scanner(System.in);
  int max  = 0;
  int cur  = 0;
  int step = 0;
  while(step++ < 4 && io.hasNextInt())
  {
    cur = io.nextInt();
    if(cur > max) max = cur;
  }
  System.out.printf("Max: %d", max);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question