0
public int rangeInScanner(Scanner stream) {
    int max = stream.nextInt();
    int min = stream.nextInt();

    while (stream.hasNextInt()){
        if (stream.nextInt() > max) {
            max = stream.nextInt();
        }
        if (stream.nextInt() < min) {
            min = stream.nextInt();
        }
    }
    return max - min;
}

为什么我不能让它工作。假设 Scanner stream = new Scanner("5, 4, 3, 2, 1"); 我希望这个返回 4。

4

1 回答 1

1

我认为应该是

public int rangeInScanner(Scanner stream) {
    int max = stream.nextInt();
    int min = max;

    while (stream.hasNextInt()){
        int curr = stream.nextInt();
        if (curr > max)
            max = curr;
        if (curr < min)
            min = curr;
    }
    return max - min;
}

编辑

您缺少一半所需的比较,并且还可能产生异常。如果有奇数个整数,nextInt将抛出NoSuchElementException

于 2013-09-14T17:20:15.863 回答