繁体   English   中英

基本Java的输出不打印。 不知道为什么

[英]Output of basic Java not printing. Can't figure out why

我是uni的新生,我们必须做一个作业,必须在整数行中找到第二小的数字。 现在我想我明白了,但我无法打印结果。 谁能弄清楚这是为什么呢?

package SecondSmallest;

import java.util.Scanner;
import java.io.PrintStream;


public class SecondSmallest {

    public static void secondSmallestLoop() {

        Scanner in = new Scanner(System.in);
        PrintStream out = new PrintStream(System.out);

        out.printf("Please enter a series of at least 2 integers: ");

        int smallest = in.nextInt();
        int secondSmallest = in.nextInt();

        while (in.hasNextInt()) {

            int next = in.nextInt();

            if (next < smallest) {
                secondSmallest = smallest;
                smallest = next;
            }

            else if (next < secondSmallest) {
                secondSmallest = next;
            }

        }

        out.print("The second smallest number is: " + secondSmallest);              
    }

    public static void main(String[] args) {
        SecondSmallest.secondSmallestLoop();
    }
}

我认为,最好有一个条件来停止扫描仪。 因此,我建议使用do-while代替。 您还应该使用System.out.println,因为可以在控制台中进行打印了。 您不必每次都实例化一个PrintStream。 顺便说一句,您的代码正在运行,但是考虑我们给您的想法将很有趣。

您的问题不是为while循环定义停止点。

in.hasNextInt()意思是:如果输入一个整数,它将继续。 要停止它,您可以输入非整数字符。

希望对您有所帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM