[英]How do you find the average of the max and min value in a String?
I am currently experimenting with Strings in Java.我目前正在尝试使用 Java 中的字符串。
For example you have a string "1234 Hello 56789"
and now you want to calculate the average of the max and min value, which is (1234/5678)/2 = 58023
.例如,您有一个字符串
"1234 Hello 56789"
,现在您要计算最大值和最小值的平均值,即(1234/5678)/2 = 58023
。
How do you do that?你是怎样做的?
I tried Integer.parseInt
which gives me an error.我试过
Integer.parseInt
这给了我一个错误。
I tried replaceAll("[^0-9]", "")
which does not get me the min and max and therefore the avg.我试过
replaceAll("[^0-9]", "")
没有得到最小值和最大值,因此没有得到平均值。 It outputs 123456789 which I do not want.它输出我不想要的 123456789。
I also tried replaceAll("[^0-9]", "").split("\\\\D+")
which just gives me 1234 56789
, but I don't know how to get the min and max.我也试过
replaceAll("[^0-9]", "").split("\\\\D+")
1234 56789
给了我1234 56789
,但我不知道如何获得最小值和最大值。
I also tried
replaceAll("[^0-9]", "").split("\\\\D+")
我也试过
replaceAll("[^0-9]", "").split("\\\\D+")
This is a good first step.这是很好的第一步。 It will give you an array of strings (
String[]
).它会给你一个字符串数组(
String[]
)。 It is probably a good idea to then convert this to an int[]
.然后将其转换为
int[]
可能是个好主意。 See Converting a String array into an int Array in java请参阅在 java 中将字符串数组转换为 int 数组
Once you have an int[]
, you can calculate the max and the min by referring to Finding the max/min value in an array of primitives using Java一旦你有一个
int[]
,你可以通过参考在使用 Java 的原语数组中查找最大值/最小值来计算最大值和最小值
By the way, the average is not (1234/5678)/2.顺便说一下,平均值不是 (1234/5678)/2。 It is (1234 + 5678)/2
它是 (1234 + 5678)/2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.