[英]Computing the sum of values that came from a split String in an array in Java
基本上我想知道如何制作一个方法,它接受一个由空格分隔的一系列十进制数字的字符串然后(根据单独的数字拆分字符串后)返回一个double。 然后使用返回的双精度数,返回舍入到最接近的整数的所有十进制数的总和。
示例:就像让我们说我输入字符串“42.5 7.2 1.2”并且我想让它返回舍入到最接近的整数的所有十进制数的总和,这里将是51.0。
这是我到目前为止的尝试。
String s = text1;
String[] ls;
ls = s.split(" ");
for(int i = 0; i<= s.length(); i++){
double a = Double.parseDouble(ls[i]);
String.split
开始,这将返回一个String
数组 double
set数组,其大小与String
数组相同 String
数组并将每个值解析为double
,将它们添加到double
数组中 double
数组。 double
数组,将每个值添加到double
类型的sum
值。 Math.round
对结果进行舍入 看看Arrays和Control Flow Statements ,特别是The for Statement
...创建一个double
数组......
String[] ls = s.split(" ");
double[] doubles = new double[ls.length];
...迭代这个String
数组并将每个值解析为double
...
for (int index = 0; index < ls.length; index++) {
doubles[index] = Double.parseDouble(ls[index]);
}
像这样的东西?
public double getSum(String dec)
{
String[] nums = dec.split(" ");
double total = 0;
for(String a : nums)
total += Double.parseDouble(a);
return Math.round(total);
}
阅读输入就行了
public void read()
{
Scanner scan = new Scanner(System.in);
//declare variable
variableHere = scan.nextLine() scan.nextInt() or w.e. you want
}
public float rnd (String st) {
String[] v = st.split(" ");
float sum = 0.0f;
for (String s : v) {
sum += Float.valueOf(s);
}
return(Math.round(sum));
}
或者用int
返回替换float
返回(这个问题不是很清楚)。
你需要这样的东西(如果我理解你的问题):
public static double roundedSum(String s) {
String[] ls = s.split(" ");
double sum = 0;
for(int i = 0; i < ls.length; i++){
sum += Double.parseDouble(ls[i]);
}
return Math.round(sum);
}
然后测试它:
public static void main(String[] args) {
String s = "42.5 7.2 1.2";
System.out.println ( roundedSum(s) ); // prints 51.0
}
作为一个注释,你的for循环是错误的:
for(int i = 0; i<= s.length(); i++){
首先,你永远不能去<=
长度(除非你减去1)。 索引从0
开始,因此字符串的最后一个位置是长度 - 1。
另外,你使用的是字符串的长度; 你需要使用数组的长度作为绑定。
这有效
package Split;
public class Split {
public Split(){
addEm("42.5 7.2 1.2");
}//constructor
private void addEm(String st) {
int i =0;
int len = st.length();
double sum =0 ;
String s = "";
st.charAt(0);
for(int j =0; j< len;j++ ){
s = s+st.charAt(j);
if(st.charAt(j)==' ' || j==len-1){
sum = sum + Double.parseDouble(s);
s = "";
}
}
System.out.print(sum);
}
public static void main (String args[]){
new Split();
}
}
输出看起来像这样
50.900000000000006 ...
在输出之前将值向上舍入为int
如果我想避免所有舍入问题,但不关心使用数组或使用双打,我可能会这样做。
public double splitAndSum(String input) {
BigDecimal sum = BigDecimal.ZERO;
for (String number : input.split("\\s+")) {
sum = sum.add(new BigDecimal(number));
}
return sum.round(new MathContext(0)).doubleValue();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.