Disclosure: When you purchase a service or a product through our links, we sometimes earn a commission.

Java Program to show Maximum and Minimum

September 17, 2017

This Java program prints the maximum and the minimum number of a given numerical digit.

For example – typical output would be

Please enter a number

42308

and theoutput is –  minimum digit is 0 and the maximum digit is 8

 



/** Method that shows the minimum and maximum digit
  *of any given number
 **/
import java.util.*;
public class MaxMin {
	
	static void maxMin(int number){

		int digit = 0;
		int min = number;
		int max = 0;

		while (number!=0){

			digit = number%10;
			number = number/10;

			if(max < digit){ max = digit; } if( min > digit) {
				min = digit;
			}
		}
			System.out.println("Max: " + max);
			System.out.println("Min: " + min);
	}

	public static void main( String[] args) {

		System.out.println("Please enter a number");
		
		Scanner console = new Scanner(System.in);
		
		// Make sure user enters only int number
		while(!console.hasNextInt()) {
			System.out.println("Please enter an int number " +
				"maximum of 10 digits");
			console.next();}

		int number = console.nextInt();

		maxMin(number);

		}
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *