分割后的java字符串的最大值

时间:2020-01-29 22:40:41

标签: java sorting split max

我正在学习初学者的Java课程,并且我有这样的任务:

用户输入单词+数字,例如“动物” +“年龄”:

马:3
dog:5
parrot:2
cat: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

所以一半的代码是一团糟,我被卡住了。 请帮助我,如果您能给出解释,那就太好了,谢谢! :)

1 个答案:

答案 0 :(得分:1)

找到最大值时,请将最大值设置为可能的最小值。那将是

maxAge = Integer.MIN_VALUE

然后设置一个这样的字符串变量。

String oldestAnimal = "";

现在,当您遍历值时,将current agemax进行比较。如果年龄较大,请设置 max to age并设置与该年龄相关的oldestAnimal to the animal

比较结果如下:

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

完成后,您将得到结果。