Computer Science, asked by aditisingh3707, 8 months ago

Write a java program to input 20number from the user and print the maximum and minimum number entered by the user

Answers

Answered by kumarisangita
0

Answer:

Today's programming exercise for a beginner is to write a Java program to take input from the user and find out maximum and minimum number and print them into the console. The purpose of this article is to teach you how to get input from a user in Java and how to use java.lang.Math class to perform some mathematical operation e.g. max, min or average. You can use Scanner class, added in Java 1.5 to read user input from the console. Scanner needs an InputStream to read data and because you are reading from the console, you can pass System.in, which is InputStream for Eclipse console, or command prompt, depending upon what you are using. This class also helps you to convert user input into requiring data type e.g. if a user enters numbers then you must convert then into int data type and store them into int variable as shown in our example. You can use nextInt() method to read user input as Integer.

Similarly, you can use nextLine() to read user input as String. There are other methods available to read a float, double, or boolean from the command prompt. Once you got both the numbers, it just matters of using relational operator less than and greater than to find smaller and larger number, as shown in the following the example.

After that you can Math.max() to find the maximum of two numbers, it should be same as your earlier result. Similarly, we will ask User to enter the number again and will display a minimum of two.

Maximum and Minimum Example in Java

Our example program has two parts. In the first part, we take input from a user, uses if block and relational operator to find maximum value and further used Math.max() method for the same purpose. In the second part of the program, we have asked the user to enter two more numbers and then we use less than the operator and if block to find smaller of two. After that, we have used Math.min() function to calculate minimum number again. If your program is correct then both output should be same.

I also suggest you to read Head First Java 2nd Edition book, if you have just started learning Java. It is one of the best books to learn Java in quick time.

calculating maximum and minimum in Java program

Java Program to calculate Maximum and Minimum of Numbers

Here is our sample Java program to calculate and print maximum and minimum of two numbers entered by the user in command prompt. You can run this program from Eclipse IDE by just copy pasting after creating a Java project and selecting it. Eclipse will automatically create a source file with the same name as the public class and put it right package. Alternatively, you can also run this program from the command prompt

Similar questions