gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 07:53:33 27 4
gpt4 key购买 nike

用户输入一个类似数组的输入,如下所示: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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com