[英]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 age
与max
进行比较。 如果年龄较大,则将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.