如何从字符串中提取数值并添加这些数字?

时间:2015-10-07 16:21:21

标签: 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");
        }
    }

}

2 个答案:

答案 0 :(得分:1)

下面应该适用于浮动和双倍。

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

答案 1 :(得分:0)

您可以使用String array{作为起始和结束位置创建}。 然后,您可以使用,作为分隔符进行拆分。然后使用parseInt转换为整数并添加到total

public static void main (String[] args) throws java.lang.Exception
{
    String a = "int[]num=new int[]{1,2,3,3,1,2}";

    if (a.substring(a.indexOf('{') + 1, a.indexOf('}')).matches("^[1-3,]+")) {
        String[] b = a.substring(a.indexOf('{') + 1, a.indexOf('}')).split(",");
        int sum = 0;
        for (String s: b)
        {
            sum += Integer.parseInt(s);
        }
            System.out.println(sum);
    }
}

Here是工作演示。这仅限于您提供的输入。如果您认为输入可能不同,请调整一下。

编辑: 我没有看到数字只能是1,2或3.我们可以使用regex来验证输入