说我在字符串中有几个数字: String line =“564 33 654 8321 15”; 现在想要找到这个字符串中最大的数字。 实验室给我getLargest()方法的算法帮助:
largest = really small number;
while(there are more number to check)
{num= get current number
if(num > largest)
largest=num
}
有人可以帮我弄清楚如何做这个“getLargest”方法吗?
答案 0 :(得分:3)
提示:
将字符串分成几部分;例如阅读String.split(...)
的{{3}}。
将字符串转换为整数;例如阅读Integer.parseInt(...)
的{{3}}。
其余的是一个循环和一些简单的逻辑。
如果您在理解这些提示时遇到问题,请使用“评论”。
(我不打算给你示例代码,因为我认为你会通过自己的工作来学习更多。)
答案 1 :(得分:1)
请记住,您不会从在线人员完成家庭作业中学到任何东西。您可以从中学到一些东西,然后再尝试自己。我在解决方案中加入了评论。
public static void main(String[] args) {
//The line is a String, and the numbers must be parsed to integers
String line = "564 33 654 8321 15";
//We split the line at each space, so we can separate each number
String[] array = line.split("\\s+");
//Integer.MIN_VALUE will give you the smallest number an integer can have,
//and you can use this to check against.
int largestInt = Integer.MIN_VALUE;
//We iterate over each of the separated numbers (they are still Strings)
for (String numberAsString : array) {
//Integer.parseInt will parse a number to integer from a String
//You will get a NumberFormatException if the String can not be parsed
int number = Integer.parseInt(numberAsString);
//Check if the parsed number is greater than the largestInt variable
//If it is, set the largestInt variable to the number parsed
if (number > largestInt) {
largestInt = number;
}
}
//We are done with the loop, and can now print out the largest number.
System.out.println(largestInt);
}