在Java中将具有多个数字的字符串转换为整数

时间:2018-10-25 01:55:46

标签: java

package averagewithmethods;

/**
*
* @author ryost
*/
import java.util.Scanner;
public class AverageWithMethods {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {       
    String inputString = inputNumberString();
    double average = averageNumbers(inputString);
    System.out.print(average);
}
/**
 * A method to get the number string from the user
 * @return String inputString
 */
public static String inputNumberString() {
    Scanner in = new Scanner(System.in);
    String inputString;
    System.out.print("Enter between 5 and 10 numbers, separated by spaces, 
to be averaged: ");
    inputString = in.nextLine();
    return inputString;
}

运行此代码时,出现以下错误:

Exception in thread "main" java.lang.NumberFormatException: For input string: "5 10"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:580)
    at java.lang.Integer.parseInt(Integer.java:615)
    at averagewithmethods.AverageWithMethods.averageNumbers(AverageWithMethods.java:47)
    at averagewithmethods.AverageWithMethods.main(AverageWithMethods.java:20)
C:\Users\ryost\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 5 seconds)

我正在尝试让用户输入字符串,然后返回平均值。我遇到的最大问题是将字符串中的每个单独的整数转换为单独的整数,以便能够计算平均值。

示例-输入:5 10 20 10 5
输出:平均值为10

 public static double averageNumbers(String inputString) {
    double average;
    int numSpaces;
    int a = 0;

    inputString = inputString.trim();
    numSpaces = inputString.length() - inputString.replaceAll(" ", "").length();
    for (int i = 0; i < (numSpaces + 1); i++) {
        a = Integer.parseInt(inputString.substring(i));
    }
    average = a / (numSpaces + 1);
    return average;
}

1 个答案:

答案 0 :(得分:0)

您应该使用split

int sum = 0;

String inputString = "5 10 20 10 5";
String []arr = inputString.split(" ");

for (String str : arr) {
    sum += Integer.parseInt(str);   //+= here
}

System.out.println("Average is " + (double) sum / arr.length);