java find smallest number in array code example
Example 1: find the largest and smallest number in an unsorted integer array in Java
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Number of integers to enter:");
int numberEnter = keyboard.nextInt();
int numbers[] = new int[numberEnter];
int pos = 0;
do {
System.out.printf("Please enter integer #%d/%d:%n", pos, numberEnter);
numbers[pos++] = keyboard.nextInt();
} while (pos < numberEnter && keyboard.hasNextInt());
int min = numbers[0];
int max = numbers[0];
for (pos = 1; pos < numbers.length; pos++) {
if (numbers[pos] < min) {
min = numbers[pos];
}
if (numbers[pos] > max) {
max = numbers[pos];
}
}
System.out.printf("%s Min: %d Max: %d%n", Arrays.toString(numbers),
min, max);
}
Example 2: how to find the smallest numbers in an arraylist java
import java.util.ArrayList;
import java.util.Scanner;
public class IndexOfSmallest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<>();
while (true) {
int input = Integer.valueOf(scanner.nextLine());
if (input == 9999) {
break;
}
list.add(input);
}
System.out.println("");
int smallest = list.get(0);
int index = 0;
while (index < list.size()) {
if (list.get(index) < smallest) {
smallest = list.get(index);
}
index++;
}
System.out.println("Smallest number: " + smallest);
index = 0;
while (index < list.size()) {
if (list.get(index) == smallest) {
System.out.println("Found at index: " + index);
}
index++;
}
}
}