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

2 番目に小さい数値のみを更新する必要がある場合、2 番目のケースを見逃している可能性があります。

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