将包含空格的字符串解析为整数数组

时间:2015-03-20 09:40:29

标签: java

这里有一个错误,即在整数数组中添加空格。结果工作正常但抛出异常错误。不知道我该如何解决?

Exception in thread "main" java.lang.NumberFormatException: For input string: " "
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:569)
    at java.lang.Integer.parseInt(Integer.java:615)
    at menu.main(menu.java:167)

4 个答案:

答案 0 :(得分:1)

我认为这就是你要找的东西:

public static void main(String[] args) {
    String s="0 1 0 1 1 1 0";
    System.out.println(Arrays.toString(s.split("\\s+")));
}

O / P:

[0, 1, 0, 1, 1, 1, 0]

答案 1 :(得分:0)

List<String> output = new ArrayList<String>();
for(String stringToAdd : youString.split(" "))
    output.add(Integer.parseInt(stringToAdd));

答案 2 :(得分:0)

喜欢这个吗?

    public static void main(String[] args) {
    String s = "3 4 6 78 a 8 9";
    String[] ss = s.split(" ");
    List<Integer> list = new ArrayList<Integer>();
    for (int i = 0; i < ss.length; i++) {
        try {
            int val = Integer.valueOf(ss[i]);
            list.add(val);          
        } catch (NumberFormatException e) {
            System.err.println(ss[i] + " is not a number");
        }

    }
    list.toArray();
}

答案 3 :(得分:-2)

Integer.parseInt(" "); // you are passing empty string to parse function.

int value;
if(!stringValue.trim().equals("")){
  value=Integer.parseInt(stringValue);
}
else{
 // assign the 0 value of whatever suits your requirements 
}