查找扫描仪中的整数范围

时间:2013-09-14 16:52:04

标签: java range

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。

1 个答案:

答案 0 :(得分: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