Java最大,最小

时间:2016-10-24 18:59:21

标签: java largenumber

我的程序有点问题。我需要让用户输入他们想要的数量,然后程序将告诉他们什么是最小和最大的数字。我的问题是,当完成所有操作时,它打印出“最大数字为0”和“最小数字为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

1 个答案:

答案 0 :(得分:-1)

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));
  }
}