簡體   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