簡體   English   中英

java分割后字符串的最大值

[英]java maximum value of string after split

我正在學習初學者的 Java 課程,我有這樣的任務:

用戶輸入單詞+數字,例如“動物”+“年齡”:

馬:3
狗:5
鸚鵡:2
貓:7

我必須讓程序打印出最古老動物的年齡。 例如像這樣:

最老動物的年齡是:7

現在,這就是我到目前為止所寫的內容。 我的問題是我不知道如何讓程序比較數字......

    while (true) {

        String luettu = x.nextLine();   // user inputs animals and numbers
        if (dataIn.equals("")) {        // when inputs nothing program stops
            break;
    }
        // Here I separate the animal and number with star symbol
        String[] separatedData = dataIn.split(":"); 

        // From now on, I'm supposed to focus on the numbers, create the rule for how to find the highest value

        x = x Integer.valueOf(separatedData[1]);  // Must target the values in the index 1 (the numbers)  but how?
    }
    int maxNumber = separatedData.lenght; 
    int i = 0;

    // I don't know how to loop and compare the numbers... and I thin "while" doesn't make sense here
    while ( i < size of separatedData) {
        if(maxNumber < separatedData) {
            maxNumber = separatedData;
        }
    System.out.println("The age of the oldest animal is: " + maxNumber); // printing the result

所以一半的代碼是一團糟,我被卡住了。 請幫助我,如果你能給出解釋,那就太好了,謝謝! :)

當找到某事物的最大值時,將最大值設置為可能的最小值。 那將是

maxAge = Integer.MIN_VALUE

然后像這樣設置一個字符串變量。

String oldestAnimal = "";

現在,當您遍歷這些值時,將current agemax進行比較。 如果年齡較大,則將max to age設置max to age並將oldestAnimal to the animal設置oldestAnimal to the animal與該年齡相關聯oldestAnimal to the animal

比較如下:

if (age > max) {
   // set appropriate values.
}

完成后,您將得到結果。

暫無
暫無

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

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