java - 如何从字符串中提取数值并将这些数字相加?

标签 java arrays string input java.util.scanner

用户输入一个类似数组的输入,如下所示:int[]num=new int[]{1,2,3}。该程序应该只接受数字 (1,2,3) 并删除逗号以添加这些数字。最后它应该打印出总和。怎么解决?

[注意:我希望用户可以在大括号内输入任意长度的数字。]

public static void main(String[] args) {
    System.out.println("Step:1. This program takes input in the following structure that looks like array declaration:\nint[]num=new int[]{1,2,3}");
    System.out.println("Step:2. The program should ignore all the strings and accept only the numeric value (i.e. in this case it is: 1,2,3).");
    System.out.println("Step:3. The program then add the numners (i.e. 1+2+3) and print out the sum");
    System.out.println("***********************\n");

    Scanner sc = new Scanner(System.in);
    System.out.println("Write input: ");
    while (true) {
        String array = sc.nextLine();
        if (array.contains("int")) {

            int convertArrIntoNum = Integer.parseInt(array.substring(20, 2));
            //remove the comma in between of each numeric value
            //add the numbers
            //print out the result
           // System.out.println("The sum of the array: " + sumResult);

        } else {
            System.out.println("Wrong input! Try again");
        }
    }

}

最佳答案

下面的内容甚至适用于 float 和 double。

import java.util.Scanner;

public class TestMainResuse {

    public static void main(String[] args) {
        System.out.println("Step:1. This program takes input in the following structure that looks like array declaration:\nint[]num=new int[]{1,2,3}");
        System.out.println("Step:2. The program should ignore all the strings and accept only the numeric value (i.e. in this case it is: 1,2,3).");
        System.out.println("Step:3. The program then add the numners (i.e. 1+2+3) and print out the sum");
        System.out.println("***********************\n");

        Scanner sc = new Scanner(System.in);
        System.out.println("Write input: ");
        while (true) {
            try {
                String array = sc.nextLine();
                if (array.contains("int") || array.contains("float") || array.contains("double")) {

                    double sum = 0;
                    int start = array.indexOf('{');
                    int end = array.indexOf('}');
                    String strNum = array.substring(start+1, end);
                    String[] strArray = strNum.split(",");
                    for (String s : strArray) {
                        sum += Double.parseDouble(s.trim());  
                    }
                    System.out.printf("The sum of the array: %.5f", sum);

                } else {
                    System.out.println("Wrong input! Try again");
                }
            } catch (Exception e) {
                System.err.println("Wrong input! Try again");
            }
        }

    }

}

测试1

Write input: 
double[] d= new double[]{1.2,3.333}
The sum of the array: 4.53300

测试2

Write input: 
int[]num=new int[]{1,2,3}
The sum of the array: 6.00000

测试3

Write input: 
float[] num = new float[]{9.1,0.5,0.6}
The sum of the array: 10.20000

关于java - 如何从字符串中提取数值并将这些数字相加?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32997496/

相关文章:

java - 是否可以同时读取和写入文件?

c# - 如何创建枚举数组

Java迷宫最短路径误解

c - 如何更改 char* 全局?

c - 在 C 程序 xCode 中包含 XML 多字符串

java - DropDownChoice - 没有选择,值 -1?

java - 基于 JPA Criteria 的查询,一次与三个查询相交

c++ - 验证 _snprintf 中的格式说明符 - C++

java - android中的对象类

javascript - 将数组 block 分成组 - 我的代码有什么问题?