Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何从字符串中提取数值并添加这些数字?_Java_Arrays_String_Input_Java.util.scanner - Fatal编程技术网

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

Java 如何从字符串中提取数值并添加这些数字?,java,arrays,string,input,java.util.scanner,Java,Arrays,String,Input,Java.util.scanner,用户输入类似数组的输入,如下所示:int[]num=newint[]{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 l

用户输入类似数组的输入,如下所示:
int[]num=newint[]{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");
        }
    }

}

您可以使用
{
}
作为起始和结束位置来创建
字符串数组。
然后可以使用
作为分隔符进行拆分。然后使用
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);
    }
}
这是工作演示。这仅限于您提供的输入。如果您认为输入可能不同,请进行调整

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

即使对于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
publicstaticvoidmain(字符串[]args){
System.out.println(“步骤:1.此程序采用如下类似数组声明的结构进行输入:\nint[]num=new int[]{1,2,3}”);
System.out.println(“步骤:2.程序应忽略所有字符串,只接受数值(即在本例中为:1,2,3)。”;
System.out.println(“步骤:3.程序然后添加numner(即1+2+3)并打印出总和”);
System.out.println(“*********************************\n”);
整数和=0;
试一试{
扫描仪sc=新的扫描仪(System.in);
System.out.println(“请输入数组长度”);
int arraylength=sc.nextInt();
System.out.println(“请输入编号”);
int[]数字=新的int[arraylength];
for(int i=0;i
您可以在两个“{”、“}”之间设置子字符串,然后对该字符串返回的字符串调用split函数。提示:1.使用string类中的
索引
,将其子字符串化。2.String[]nums=thatString.split(“,”);这也适用于输入-
{2,45,4}
,这是错误的,因为这不符合OP的要求。@hagrawal Oh。我没有读那部分。我们可以添加条件来检查它是否包含除
1,2,3
@hagrawal check edit之外的任何内容。它只接受
1,2,3
only:)不,我的意思是希望输入是一个有效的数组声明,如果作为
{1,2,44}
的输入被传递,您的答案也会起作用。可以传递任何数字,但它应该是有效的数组声明。@hagrawal问题的措辞令人困惑<代码>程序应该只接受数字(1,2,3).
我想OP不会介意您是否可以编辑问题,以便我们可以更好地回答。我想你明白OP的意思了
     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");
     int SUM = 0 ;
    try {


 Scanner sc = new Scanner(System.in);
    System.out.println("Please enter array length");
    int arraylength = sc.nextInt();
    System.out.println("Please enter number");



int[] numbers = new int[arraylength];

for (int i = 0; i < numbers.length; i++)
{    
    while (!sc.hasNextInt()) 
        sc.next();

    numbers[i] = sc.nextInt();
    SUM+=numbers[i] ;
} 
        System.out.println( "sum is "+ SUM);    ;

        } catch (InputMismatchException e) {
            System.out.println("enter interger");
    }
}