Java 如何在一行代码中求和值除以逗号?
我需要将字符串“2,4,5”中的值除以逗号求和。当然,我可以这样做:Java 如何在一行代码中求和值除以逗号?,java,Java,我需要将字符串“2,4,5”中的值除以逗号求和。当然,我可以这样做: String[] str = "2,4,5".split(",") int total = 0; for (int i=0; i<str.length; i++) { total += str[i]; } String[]str=“2,4,5”。拆分(“,”) int-total=0; 对于(int i=0;i为了求和,必须首先将字符串转换为数字 大概是这样的: int total = Stream.of ("2,
String[] str = "2,4,5".split(",")
int total = 0;
for (int i=0; i<str.length; i++)
{
total += str[i];
}
String[]str=“2,4,5”。拆分(“,”)
int-total=0;
对于(int i=0;i为了求和,必须首先将字符串转换为数字
大概是这样的:
int total = Stream.of ("2,4,5".split(",")).mapToInt(Integer::parseInt).sum();
String[] str = "2,4,5".split(",");
int total = 0;
for (String str1 : str) {
total += Integer.parseInt(str1);//Convert your String to int
}
Stream.of()
将字符串[]
转换为流
mapToInt(Integer::parseInt)
将该流转换为IntStream
(通过对每个字符串应用Integer.parseInt()
)具有方便的sum()
方法
您可以这样做:
Stream.of("2,4,5".split(",")).mapToInt(Integer::parseInt).sum();
您不能将int
求和为Strings
,您必须将String
转换为int
,您可能需要这样的东西:
int total = Stream.of ("2,4,5".split(",")).mapToInt(Integer::parseInt).sum();
String[] str = "2,4,5".split(",");
int total = 0;
for (String str1 : str) {
total += Integer.parseInt(str1);//Convert your String to int
}
如果您使用的是java 8,@Eran和@Justas的解决方案是完美的您只需在一行中编写上述代码即可。:)您需要的是一个表达式。