找到最小和最小的数字

时间:2014-09-06 13:39:51

标签: java loops

该程序应该在x个数字中找到最小和第二个最小的数字。 程序每次都找到最小的数字,但是我在键盘上替换第二个最小的数字时遇到了问题。

 System.out.println("How many numbers?");
 int total = keyboard.nextInt();

 System.out.println("What is the first number");
 int small = keyboard.nextInt();

 System.out.println("whats the second number");
 int nest = keyboard.nextInt();
 // Assigning the first two numbers to smallest and second largest

 for (int i =2;i<total;i++) {                     
    System.out.println("whats the next number?");
    int number = keyboard.nextInt();

    if (number < small) {
       small = number;
    } // this part works (I think)

    if ((number > small) && (number < nest)) {
       nest = number;
    }//this part dont (I think)

 }//end forloop
 System.out.printf("The smallest numbers are %d and %d",small,nest); 

2 个答案:

答案 0 :(得分:1)

你必须得到正确的订单。首先,查看数字是否小于最小数字,如果是,请替换它并将旧的最小数字移动到第二个最小数字。否则,如果它小于第二个最小数字,则替换它。

这是应该在循环中的代码:

if (number < small) {
    nest = small;
    small = number;
} else if (number < nest) {
    nest = number;
} 

答案 1 :(得分:0)

将所有数字添加到LinkedList<Integer>,然后对List进行排序。 List中的前两项将是最小的。

public class Sorter {

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        List<Integer> numbers = new LinkedList<Integer>();

        System.out.println("How many numbers?");
        int total = keyboard.nextInt();

        System.out.println("What is the first number");
        numbers.add( keyboard.nextInt());
        System.out.println("whats the second number");
        numbers.add( keyboard.nextInt());
        // Assigning the first two numbers to smallest and second largest

        for (int i =2;i<total;i++) {                     
        System.out.println("whats the next number?");
        numbers.add( keyboard.nextInt());
        }//end forloop

        Collections.sort(numbers);

        System.out.printf("The smallest numbers are %d and %d",numbers.get(0),numbers.get(1)); 

    }
}