簡體   English   中英

在循環中輸入一系列數字后找到最小整數

[英]Finding the minimum integer after entering a series of numbers in a loop

嗨,每個人都可以告訴我如何找到循環中一系列整數的最小整數? 我正在使用掃描儀類來獲取用戶的輸入,並且我實現了一個 do-while 循環,因為當輸入為 0 時循環終止。然后程序輸出結果。

到目前為止,我在循環中的代碼是這樣的

Scanner console = new Scanner(System.in);
    int choice = 0;
    int sumPositive = 0;
    int sumOdd = 0;
    int count = 0;
    int min=99999999;
    do {
        choice = console.nextInt();
        if (choice < min) {
            min = choice;
            } // setting the minimum number
        if (choice > 0) {
            sumPositive += choice;
            count++;
        } // positive numbers sum and count
        if (choice % 2 == 1 && choice > 0) {
            sumOdd += choice;
        } // odd numbers sum

    } while ( choice != 0);

使用而不是當 choice == 0 然后你的 min 變成 0。

像這樣的事情應該有效。

public int findLowestNumberInSeries() {
    Scanner console = new Scanner(System.in);
    int lowest = Integer.MAX_VALUE;
    int input;
    do {
        input = console.nextInt();
        if (input < lowest) {
            lowest = input;
        }
    }
    while (input != 0);
    return lowest;
}

您所要做的就是將int min = 99999999更改int min = Integer.MAX_VALUE並在最后打印min的值。 干杯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM