Java程序在控制台输入中找到第二小的数字



我确实在努力解决这个问题,但如果没有帮助,就无法继续下去。我的逻辑是正常的,但由于某种原因,它无法正常执行。

在执行时,我想输入一行数字,例如10 12 5 9 3,程序应该返回第二小的数字。由于我想首先控制基础知识,所以除了使用的两个类之外,我不使用任何其他导入的类。

如果有人能阐明为什么这不起作用,我将不胜感激。

package secondSmallest;
import java.util.Scanner;
import java.io.PrintStream;
public class secondSmallest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
PrintStream out = new PrintStream(System.out);

int smallest = 1;
int secsmallest = 0;
int hold = 0;

while(scan.hasNext()); {

hold = scan.nextInt();

if (hold < smallest) {
smallest = secsmallest;
smallest = hold;


} else {
hold = scan.nextInt();
}

out.printf(" %d", secsmallest);
}
}
}

首先:

我的逻辑是有序的,但由于某些原因,它无法正常执行。

表示您的逻辑不正常(除非只是拼写错误或其他语法错误,阻塞了完美的结果(;


第二:

Scanner#hasNext(),作为while条件:

如果此扫描程序的输入中有另一个令牌,则返回true。此方法可能在等待扫描输入时发生阻塞。扫描仪不会前进超过任何输入。

并且您应该在某个地方,以某种方式,指示您希望while循环何时结束。在您的示例中,您的循环将无限地进行,因为它没有任何基本情况。即使是";输入";按键是一个数据,按下它将不断输入新的行控制字符;


第三:

您将最小值初始化为1,这并不是一个将常量静态分配给当前最小值的干净设计。当你的输入不同时,考虑一种可能性;


第四:

您正在while循环中打印secsmallest,我想这不是您想要做的;


第五:

通过读取elsehold = scan.nextInt();,您有效地提交了一个输入,当您的while向前迭代一步时,您就有了另一个hold = scan.nextInt(); and you jump one iteration


第六:

有许多方法可以设计";找到第二小的";算法(先对其进行排序,然后取第二个元素;引入两个指针;等等(,但如果您坚持按照自己的方式进行操作,这会如预期的那样起作用:

public class Main {
public static void main(String[] args) {
int[] arr = {10, 12, 5, 9, 32, 5, 123, 4, -34, 12, -534, -53, -1, 432, 53};
int res = secondSmallest(arr);
System.out.println(res);
}
public static int secondSmallest(int[] arr) {
int smallest = arr[0];
int secsmallest = arr[1];
int i = 2;
while (i < arr.length-1) {
int current = arr[i];
if (current < smallest) {
secsmallest = smallest;
smallest = current;
}
else if(current < secsmallest) {
secsmallest = current;
}
i++;
}
return secsmallest;
}
}

输出:

-53

您的程序应该看起来像这个

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
PrintStream out = new PrintStream(System.out);
int smallest = Integer.MAX_VALUE;
int secSmallest = smallest;
int hold = 0;
while (scan.hasNextInt()) {
hold = scan.nextInt();
if (hold < smallest) {
secSmallest = smallest;
smallest = hold;
} else if (hold < secSmallest) secSmallest = hold;
}
out.printf(" %d", secSmallest);
}

最新更新