找到第二个最小整数时输出不正确

时间:2013-11-11 15:33:01

标签: java loops for-loop while-loop

以下代码仅偶尔会返回正确的值,并且当它执行时它似乎完全随机,并且它没有。指针好吗?

/*This program takes a series of integers as user input
 * and returns the second smallest amongst them to the
 * console. 
 * 
 * For reasons unknown to the programmer, ending user 
 * input with Ctrl-D only works occasionally. If Ctrl-D
 * fails, enter any character(s) to the console and press 
 * enter. Make sure the dummy characters are separated 
 * from any integers with whitespace. The program should 
 * execute normally, ignoring the dummy character(s).
 * 
 * Written by xxxxxx, w45-2013*/

package secondSmallest;

import java.io.PrintStream;
import java.util.Scanner;

public class SecondSmallest {

    PrintStream out;
    Scanner in;

    SecondSmallest() {
        out = new PrintStream(System.out);
        in = new Scanner(System.in);
    }

    void start() {
        out.printf("Enter 3 or more positive integers, seperate with whitespace. End input with Ctrl-D.%nInteger input:");
        int smallest, secondSmallest = 2147483647, nextInt;
        smallest = in.nextInt();
        while (in.hasNextInt()) {
            nextInt = in.nextInt();
            if (nextInt < smallest) {
                secondSmallest = smallest;
                smallest = nextInt;
            }
        }
        out.printf("The second smallest integer is %d", secondSmallest);
    }

    public static void main(String[] args) {
        new SecondSmallest().start();
    }
}

1 个答案:

答案 0 :(得分:2)

当只需要更新第二个最小数字时,你可能会错过第二种情况:

if (nextInt < smallest) {
    secondSmallest = smallest;
    smallest = nextInt;
} else if (nextInt < secondSmallest) {
    secondSmallest = nextInt;
}