1

下面的代码只是偶尔会返回正确的值,它似乎是完全随机的,什么时候没有。请指点?

/*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();
    }
}
4

1 回答 1

2

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

if (nextInt < smallest) {
    secondSmallest = smallest;
    smallest = nextInt;
} else if (nextInt < secondSmallest) {
    secondSmallest = nextInt;
}
于 2013-11-11T15:37:40.927 回答