This example will get an array of integer numbers from the command line console which the user inputs, then it will calculate the minimum number in the integer array and print the value out in the console.
1. Get The Minimum Integer Value In Java Array Source Code.
- FindMinimumValueInArray.java
package com.dev2qa.java.basic.array; import java.util.Scanner; public class FindMinimumValueInArray { public static void main(String[] args) { // Let user input a line of string numbers separated by white space. System.out.println("Input some integer seperated by white space."); // Create a Scanner object to get user input. Scanner scanner = new Scanner(System.in); String line = scanner.nextLine(); // If user input is not quit then loop. while(!"quit".equalsIgnoreCase(line)) { if(line!=null && line.trim().length() > 0) { // Give a default minimum number to the variable. int minNumber = Integer.MIN_VALUE; // Split numbers in the input string by white space. String numberArray[] = line.split("\\s+"); int length = numberArray.length; for(int i = 0; i < length; i++) { String tmpStr = numberArray[i]; // If the input string is an integer. if(isInteger(tmpStr)) { // Get current number. int currNumber = Integer.parseInt(tmpStr); // If minNumber is not assigned a number value in the string line. if(minNumber == Integer.MIN_VALUE) { // Then assign the first number to minNumber. minNumber = currNumber; }else { // If currNumber smaller than minNumber then assign it's value to minNumber. if(minNumber > currNumber) { minNumber = currNumber; } } } } // Print the minimum number value in command line console. System.out.println("The minimum number is " + minNumber + ", input quit to exit, input another line of number to execute again."); } // Get user next input string line. line = scanner.nextLine(); } } /* Check whether the string is an integer or not. */ private static boolean isInteger(String value) { boolean ret = true; try { Integer.parseInt(value); }catch(NumberFormatException ex) { ret = false; System.err.println(ex.getMessage()); }finally { return ret; } } }
- Below is the example code execution output.
Input some integer seperated by white space. 1 6 8 90 -100 The minimum number is -100, input quite to exit, input another line of the numbers to execute again. 8 9 2 3 6 The minimum number is 2, input quite to exit, input another line of number to execute again.