Java最大和最小

Java Largest and smallest

我的程序有点问题。我需要要求用户输入任意数量的数字,然后程序会告诉他们最小和最大的数字是多少。我的问题是当一切都说完了它会打印出 "the largest number is 0" 和 "the smallest number is 0"。它总是说即使我从不输入 0。我想知道程序出了什么问题。任何指针或助手都会很棒。再次重复,我遇到的问题是无论如何最小和最大都会返回 0。

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.in);
        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;
                System.out.println(large);
            }

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

我首先使用了这段代码:Java program to find the largest & smallest number in n numbers without using arrays

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(System.in); //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));
  }
}