简体   繁体   English

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

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

I'm a freshman at uni and we have to make an assignment where we have to find the second smallest number in a line of integers. 我是uni的新生,我们必须做一个作业,必须在整数行中找到第二小的数字。 Now I THINK I got it but I can't get the result to print. 现在我想我明白了,但我无法打印结果。 Can anyone figure out why this is? 谁能弄清楚这是为什么呢?

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

In my opinion, it is better to have a condition to stop your scanner. 我认为,最好有一个条件来停止扫描仪。 So I would suggest to use a do-while instead. 因此,我建议使用do-while代替。 You also should use System.out.println, because it's ready to print in your console. 您还应该使用System.out.println,因为可以在控制台中进行打印了。 You don't have to instantiate a PrintStream everytime. 您不必每次都实例化一个PrintStream。 And by the way, your code is working, but it would be interesting to consider the thoughts we gave to you. 顺便说一句,您的代码正在运行,但是考虑我们给您的想法将很有趣。

Your problem is not defined stop point for the while loop. 您的问题不是为while循环定义停止点。

in.hasNextInt() mean: If you input an integer, it will be continue. in.hasNextInt()意思是:如果输入一个整数,它将继续。 To stop it, you can input a character that isn't an integer. 要停止它,您可以输入非整数字符。

Hope to helpful 希望对您有所帮助

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

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