簡體   English   中英

編寫Java代碼以查找max&min。 如果只有一個輸入就會卡住

[英]writing java code to find max&min. getting stuck on if there's only one input

以下是我到目前為止的內容。 它起作用,但是,如果只有一個答案,則輸出之一設置為零。 有誰有解決這個問題的想法? 我的教授特別要求我們確保編寫代碼來包括這種情況。

public static void main(String[] args)
{
    String input;
    int number;
    int option;
    int min;
    int max;

    option = JOptionPane.YES_OPTION;        
    max = 0;
    min = 0;
    while (option == JOptionPane.YES_OPTION)
    {

    input = JOptionPane.showInputDialog("Enter a number: ");
    number = Integer.parseInt(input);

    if(number < max)
        min = number;
    else if(number > min)
        max = number;

    option = JOptionPane.showConfirmDialog
    (null, "Would you like to enter another number?");

    }

    JOptionPane.showMessageDialog(null, "The smallest number entered is "
    + min + ". The largest number entered is " + max + ".");
}

您的初始值是錯誤的:

max = 0;
min = 0;

如果僅輸入負數,則所有值都將小於原始的max ,因此max將保持為0。同樣,如果僅輸入正數,則所有值都將大於原始的min ,因此min將保持為0。

將它們更改為:

max = Integer.MIN_VALUE;
min = Integer.MAX_VALUE;

編輯:

你把情況倒退了。

變更:

if(number < max)
    min = number;
else if(number > min)
    max = number;

if(number > max)
    max = number;
if(number < min)
    min = number;

您的代碼甚至無法使用2個或更多的輸入(只需用相同的數字測試兩次或多次)。 要解決此問題,只需刪除“ else”,留下兩個單獨的if語句。 另外,您應該在Eran的回答中將min max設置為:

max = Integer.MIN_VALUE;
min = Integer.MAX_VALUE;

編輯:對不起,還有更多的錯誤,語句應如下所示:

if(number < min)
    min = number;
if(number > max)
    max = number;

暫無
暫無

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

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