- Maximum and minimum method java
- How to write a program in java that will take 5 integers and output the minimum and the maximum integer?
- 4 Answers 4
- How to calculate Maximum and minimum in Java? Beginner Tutorial
- How to find Maximum and Minimum Example in Java
- Java Program to calculate Maximum and Minimum of Numbers
- Get the maximum of two numbers using Math.max in Java
- Example
- Output
- Java program to find maximum and minimum number in an array
- Java Program to find the maximum and minimum number
- Java Code:
- Output:
Maximum and minimum method java
This program is supposed to find the maximum, minimum, and average of grades. User inputs int inputGrade and the program displays letter it is. It’s supposed to do this how however many students are needed. I’m having trouble writing the method where it finds the max and min. (yes I’ve talked to my teacher if anyone’s wondering. ) I pasted the methods below (they don’t work). Just like IN GENERAL, does anyone know how to find the maximum and minimum of a set of entered numbers? (not using arrays, lists, or any unusual imports other than scanner) ** note I’ve updated this a lot.
import java.util.Scanner; public class GetLetterGrade < static int inputGrade; // input grade public static void main(String [] args) < Scanner reader = new Scanner(System.in); int classAverage; int classMin; // class's minimum grade int classMax; // class's maximum grade while (inputGrade != -1) // while user is entering grades < System.out.println("Welcome to the grade calculator. \nPlease enter a numeric grade. After the last student in the class, enter a grade of -1."); inputGrade = reader.nextInt(); letterGrade(inputGrade); // calls letter grade method findMaxAndMin(); result(); >> // find letter grade public static String letterGrade(int numGrade) < String gradeMessage = ""; < if (numGrade >= 96 && numGrade > > return gradeMessage; > public static int findCharGrade(int numGrade) < char letter; if (numGrade >= 90 && numGrade else if (numGrade >= 80 && numGrade < 90) // B < letter = 'B'; >else if (numGrade >= 70 && numGrade < 80) // C < letter = 'C'; >else if (numGrade >= 60 && numGrade < 70) // D < letter = 'D'; >else if (numGrade < 60) // F < letter = 'F'; >> // finds maximum and minimum grades public static int findMaxAndMin(int inputGrade) < int max = Math.max(inputGrade, max); int min = Math.min(inputGrade, min); if (inputGrade < max) < inputGrade = max; findCharGrade(inputGrade); >else if (inputGrade > min) < inputGrade = min; findCharGrade(inputGrade); >> public static void calcAverage(int sumOfGrades, int numOfStudents) < // something goes here >// finds results public static void result() < int min = findMaxAndMin(inputGrade); int max = findMaxAndMin(inputGrade); System.out.println("Please enter a numeric grade"); int inputGrade = reader.nextInt(); letterGrade(inputGrade); if (inputGrade == -1) < System.out.println("You entered " + numOfStudents + " students. Class Average: " + average + " Class Minimum: " + min + " Class maximum: " + max + " \nThanks for using the class grade calculator!"); >>
you should initialize the max and min the other way so that the function would work i.e. max = int.min_val, min = int.max_val. and invert the if clause as well
How to write a program in java that will take 5 integers and output the minimum and the maximum integer?
I am trying to write a code that will ask for 5 integer values which I already have complete. However, now I need to know how to get my program to output the minimum and maximum values of the 5. I know that there is a possibility to use if statements but that would be 120 different if statements. I was wondering if there was an easier way to find the maximum and minimum.
4 Answers 4
Put the numbers in an array, sort the array, then take the first and last element.
Why would you need 120 different if statements? You’ve already gotten answers about calling math functions to get the job done, I’ve used a simple sorting method to get the job done.
The solution to your problem is divided into the following: 1) Reading the user input 2) Sorting that 3) Find the max min from the sorted bunch
//Import relevant packages import java.io.BufferedReader; import java.io.InputStreamReader; class MinMax < public static void main(String[] args) < int[] myArray = new int[5]; //Array to hold user input of 5 integers int[] resultArray; //reference var to hold the resultArray object //Buffered reader is wrapped around the input stream reader to read user input BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); //Loop to get user input, 5 times for (int i=1;i<=5;i++)< System.out.println("Enter a number: "); try< myArray[i-1] = Integer.parseInt(reader.readLine()); //String to integer the user input >catch(Exception e) < e.printStackTrace(); >> //Calling the function sortme() to do the sorting resultArray = sortme(myArray); //After bubble sort has sorted the input array, the min is the first and max is the last, values of the array System.out.println("The min is: " + resultArray[0] + ", and the max is: "+myArray[4]); > //Bubble sort static int[] sortme(int[] array)< int temp; for (int i=(array.length-1);i>=0;i--) < for (int j=1;j<=i;j++)< if (array[j-1] >array[j]) < temp = array[j-1]; array[j-1] = array[j]; array[j] = temp; >> > return array; >
The min is: 1, and the max is: 9
EDIT Mr. Yetti, pointed out the inefficiency of the sorting method, as it is not needed in the first place. Here is the iterating method:
import java.io.BufferedReader; import java.io.InputStreamReader; class MinMax_nosort < public static void main(String[] args) < int[] myArray = new int[5]; //Array to hold user input of 5 integers //Buffered reader is wrapped around the input stream reader to read user input BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); //Loop to get user input, 5 times for (int i=1;i<=5;i++)< System.out.println("Enter a number: "); try< myArray[i-1] = Integer.parseInt(reader.readLine()); //String to integer the user input >catch(Exception e) < e.printStackTrace(); >> minmax(myArray); > static void minmax(int[] array) < int max, min; max = min = array[0]; for (int i=1;imax) max = array[i]; else if(array[i] < min) min = array[i]; >System.out.println("The min is:" + min + " and the max, is: " + max); >
The min is:1 and the max, is: 9
How to calculate Maximum and minimum in Java? Beginner Tutorial
Today’s programming exercise for a beginner is to write a Java program to take input from the user and find out the maximum and minimum numbers 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 the Scanner class, added in Java 1.5 to read user input from the console. The 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 them into int data type and store them into int variables 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 a relational operator less than and greater than to find smaller and larger numbers, as shown in the following example.
After that you can Math.max() to find the maximum of two numbers, it should be the same as your earlier result. Similarly, we will ask the User to enter the number again and will display a minimum of two.
How to find Maximum and Minimum Example in Java
Our example program has two parts. In the first part, we take input from a user, uses the if block and relational operator to find the maximum value, and further used the 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 the minimum number again. If your program is correct then both output should be same.
Java Program to calculate Maximum and Minimum of Numbers
Here is our sample Java program to calculate and print the maximum and minimum of two numbers entered by the user in the 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 by following the steps given here.
import java.util.Scanner; import java.util.concurrent.Semaphore; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * * Java program to calculate Maximum and minimum of two numbers * entered by user in console. * * @author Javin Paul */ public class MaxMinExerciseInJava < public static void main(String args[]) throws InterruptedException < Scanner scnr = new Scanner(System.in); // Calculating Maximum two numbers in Java System.out.println("Please enter two numbers to find maximum of two"); int a = scnr.nextInt(); int b = scnr.nextInt(); if (a > b) < System.out.printf("Between %d and %d, maximum is %d %n", a, b, a); > else < System.out.printf("Between %d and %d, maximum number is %d %n", a, b, b); > int max = Math.max(a, b); System.out.printf("Maximum value of %d and %d using Math.max() is %d %n", a, b, max); // Calculating Minimum between two numbers in Java System.out.println("Please enter two numbers to find minimum of two"); int x = scnr.nextInt(); int y = scnr.nextInt(); if (x y) < System.out.printf("Between %d and %d, Minimum Number is %d %n", x, y, x); > else < System.out.printf("Between %d and %d, Minimum is %d %n", x, y, y); > int min = Math.min(x, y); System.out.printf("Maximum value of %d and %d using Math.min() is %d %n", x, y, min); > > Output Please enter two numbers to find maximum of two 10 11 Between 10 and 11, maximum number is 11 Maximum value of 10 and 11 using Math.max() is 11 Please enter two numbers to find minimum of two 45 32 Between 45 and 32, Minimum is 32 Maximum value of 45 and 32 using Math.min() is 32
That’s all about how to calculate maximum and minimum of two numbers in Java. In this tutorial, you have learned how to get input from the user, how to use a relational operator to compare two numbers, and how to use java.lang.Math class to perform common mathematical operations e.g. finding maximum and minimum of two numbers.
P. S. — If you have started learning Java in school or any training center, I suggest you keep a copy of Head First Java or Core Java Volume 1 by Cay S. Horstmann for your own reference, those are two great Java books for beginners.
Get the maximum of two numbers using Math.max in Java
To obtain the maximum of two numbers using Math.max in Java, we use the java.lang.Math.max() method. The Math.max() accepts two numbers and returns the greater of the two. The result is closer to positive infinity on the number line. Even if one of the values is not a number(NaN), the result is NaN.
Declaration — The java.lang.Math.max() method is declared as follows −
public static int max(int a, int b) public static double max(double a, double b) public static long max(long a, long b) public static float max(float a, float b)
Let us see a program to get the maximum of two numbers using the Math.max() method
Example
import java.lang.Math; public class Example < public static void main(String[] args) < // declaring and intializing some integer values int a = 10; int b = 9; // declaring and intializing some float values float c = 10.00f; float d = 9.99f; // declaring and initializing some double values double x = 300.01d; double y = 290.344d; // declaring and initializing some long values long r = 123456l; long s = 35678l; System.out.println("Maximum of " + a +" and " + b +" is " + Math.max(a,b)); System.out.println("Maximum of " + c +" and " + d +" is " + Math.max(c,d)); System.out.println("Maximum of " + x +" and " + y +" is " + Math.max(x,y)); System.out.println("Maximum of " + r +" and " + s +" is " + Math.max(r,s)); >>
Output
Maximum of 10 and 9 is 10 Maximum of 10.0 and 9.99 is 10.0 Maximum of 300.01 and 290.344 is 300.01 Maximum of 123456 and 35678 is 123456
Java program to find maximum and minimum number in an array
Java Program to find the maximum and minimum number
In the following question, we are supposed to enter N elements in a dynamic array of size n. After entering into the array, we’ll have to find and print the maximum and minimum element present in the array.
The standard algorithm will be:
- Declare a variable N to store the size of the array.
- Prompt the user to enter the size of the array and store the input in N .
- Declare an array of size N to store the integer inputs.
- Declare 2 variables, min_element and max_element , to store the minimum and maximum elements, respectively.
- Initialize min_element and max_element with the first element of the array.
- Use a loop to iterate over the array, starting from the second element.
- Within the loop, compare each element with min_element and max_element . If the current element is less than min_element , update min_element to the current element. If the current element is greater than max_element , update max_element to the current element.
- After the loop terminates, print the minimum and maximum elements found, along with a message indicating the result.
Java Code:
import java.util.*; class ArrMinMax < public static void main() < Scanner inp = new Scanner(System.in); System.out.print("\n Enter Size of Array: "); int n = inp.nextInt(); int i, sum = 0; int arr[] = new int[n]; //Creating N-size Array for (i = 0; i < n; i++) < //Entering N numbers in array System.out.print("\n Enter: "); arr[i] = inp.nextInt(); >int max_element = arr[0], min_element = arr[0]; //Initializing with first element. for (i = 0; i < n; i++) < if (arr[i] >max_element) < //Checking Maximum element max_element = arr[i]; >if (arr[i] < min_element) < //Checking Minimum element min_element = arr[i]; >> //Printing Result System.out.println("\n Maximum Number: " + max_element); System.out.println("\n Minimum Number: " + min_element); > >
Output:
Enter Size of Array: 6 Enter: 12 Enter: 36 Enter: 5 Enter: 41 Enter: 20 Enter: 36 Maximum Number: 41 Minimum Number: 5