Write a program to input 6 numbers. After each number is input, print the biggest of the numbers entered so far. Sample Run Enter a number: 1 Largest: 1 Enter a number: 3 Largest: 3 Enter a number: 4 Largest: 4 Enter a number: 9 Largest: 9 Enter a number: 3 Largest: 9 Enter a number: 5 Largest: 9

Respuesta :

Answer:

import java.io.*;

import java.util.*;

public class Main {

   public static void main(String[] args) throws IOException {

       BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

       int t = 6;

       ArrayList<Integer> list = new ArrayList<>();

       while (t-- > 0) {

           System.out.println("Enter a value");

           int value = Integer.parseInt(in.readLine());

           list.add(value);

           System.out.println("Largest: ");

           System.out.println(Collections.max(list));

       }

   }

}

Explanation:

This program is done in Java. The idea is that it takes input from a user from the BufferedReader (which is superior to the scanner, since it can read input much faster and can store more information, i.e., never use the scanner).

It will then parse the input (since it receives the input as a data type of String) to an Integer.

I initialized t as the total numbers that you want to evaluate. That's why I defined it as t = 6 since the input you want is 6.

The while loop, which checks (t-- > 0), will execute whatever is inside the loop for t amount of times (i.e., 6 times).

You also want to initialize an ArrayList outside of the while, since if you run the program by initializing every time the while loop goes back and forth, it will reset all of its content, hence outputting the maximum value as the value you enter each time.

Next, we will create a variable "value" which will take every input and parse the String as an integer.

We will do the .add function to add every single value from the input to the ArrayList, such way that it stores all of the values you want to evaluate.

Once we have done that, we want to print the max value in the list at the given moment, hence why we include the Collections.max() inside the while loop.

If you were to include it outside of the while loop, the function would print the maximum value of the total 6 numbers, and not per every value added.

Here's a sample input + output:

Enter a value

1

Largest:  

1

Enter a value

3

Largest:  

3

Enter a value

4

Largest:  

4

Enter a value

9

Largest:  

9

Enter a value

3

Largest:  

9

Enter a value

5

Largest:  

9

ACCESS MORE