gpt4 book ai didi

java - 查找第二小整数时输出不正确

转载 作者:行者123 更新时间:2023-11-30 04:09:48 25 4
gpt4 key购买 nike

下面的代码只是偶尔返回正确的值,并且当它返回和不返回时它看起来完全随机。请指点?

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

最佳答案

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

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

关于java - 查找第二小整数时输出不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19910037/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com