John Smth John Smth - 11 months ago 68
Java Question

Java Largest and smallest

I have a slight issue with my program. I need to ask the user to input as many numbers as they want and then the program will tell them what is the smallest and largest number. My issue is when all is said and done it prints out "the largest number is 0" and "the smallest number is 0". It always says that even if i never enter 0. I was wondering what was wrong with the program. Any pointers or helpers would be fantastic. Again to repeat, the issue im having is that the smallest and largest come back as 0's no matter what.

import java.util.Scanner;
public class LargestAndSmallest {

public static void main(String[] args) {
int smallest = 0;
int large = 0;
int num;
Scanner keyboard = new Scanner(;
System.out.println("Enter the numer");
int n = keyboard.nextInt();
num = keyboard.nextInt();
while (n != -99) {
System.out.println("Enter more numbers, or -99 to quit");
n = keyboard.nextInt();

for (int i = 2; i < n; i++) {
num = keyboard.nextInt();

if (num > large) {
large = num;

if (num < smallest) {
smallest = num;
System.out.println("the largest is " + large);
System.out.println("the smallest is " + smallest);

I used this code as in the first place: Java program to find the largest & smallest number in n numbers without using arrays

Answer Source
import java.util.Collections;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class LargestAndSmallest {

  public static void main(String... args) {
    final Scanner keyboard = new Scanner(; //init the scanner
    System.out.println("Enter a number");
    final Set<Integer> ints = new HashSet<>(); //init a set to hold user input
    int n; //declare a variable to hold each number
    while ((n = keyboard.nextInt()) != -99) { //loop until 99 is entered
      ints.add(n); //add user input to our set
      System.out.println("Enter more numbers, or -99 to quit.");
    //output aggregate info
    System.out.println("the largest is " + Collections.max(ints)); 
    System.out.println("the smallest is " + Collections.min(ints));