要放入Vector的字符串数组

时间:2011-05-27 04:55:42

标签: java

我在下面的代码中遇到了这个问题,因为它没有运行但是生成了nullpointer异常。我在这里尝试做的是获取输入一个字符串数组然后吐出它但逗号然后将其传递给Integer类型然后将其存储在向量中。然后从该数组中获取最大数量。代码显示没有错误,但很难找到什么错误。

import java.util.Collections;
import java.util.Vector;

public class Splitting {

  /**
  * @param   
  */

protected int[] temp;
Vector<Integer> vec = new Vector<Integer>();

public void split(String input) {
    if (input == null) {
      String[] str;
      str = input.split(",");
      temp = new int[str.length];

      for (int i = 0; i < str.length; i++) {
            temp[i] = Integer.parseInt(str[i]);
            vec.add(temp[i]);
        }
    }
    System.out.println(vec);
    Collections.sort(vec);

    System.out.println(vec);
    Collections.max(vec);
}



public static void main(String[] args) {
    // TODO Auto-generated method stub

    Splitting obj = new Splitting();

    obj.split("12,65,21,23,89,67,12");



}

}

4 个答案:

答案 0 :(得分:5)

您必须创建数组。取代

temp = null;

temp = new int[str.length];

另一个小问题:在中使用它进行拆分后,在while循环中测试input != null。因此,如果使用null值调用方法,则甚至在执行while语句之前,您将获得NPE。您可以删除while语句并添加测试

if (input == null) {
   // return or throw exception
}

在方法的开头。


你已经接近你的代码 - 我想我可以展示一个参考实现进行比较:

public void split(String input) {
  if (input == null) {
     // if the input is null, print a message and return
     System.out.println("Input must not be null");
     return;
  }

  String[] numbers = input.split(",");  // changed the name to show the content
  int[] temp = new int[numbers.length];

  for (int i=0; i < numbers.length; i++) {
     try {
        temp[i] = Integer.parseInt(str[i]);
     } catch (NumberFormatException nfe) {
        // if a number can't be parsed, print a message and return
        System.out.println("Input contains an illegal entry (non-integer value");
        return;
     }
     vec.add(temp[i]);
  }
  System.out.println(vec);
  Collections.sort(vec);

  System.out.println(vec);
  Collections.max(vec);
}

答案 1 :(得分:1)

你的问题在于temp = null;这一行。删除此行。这就是你的NPE。您正在尝试访问空字段。

而是在split方法中声明temp。

int [] temp = new int [str.length];

答案 2 :(得分:1)

CoolBeans和AndreasD指出temp不应该初始化为null。让我补充一点,temp不应该作为数组存在,句号。您正在创建一个重复的结构,一次作为数组temp,另一次作为Vector vec。

所以,这里有一些可能的变化。 temp只是变成了一个int(不是数组),而且只要temp[i],就会变成temp。或者,完全摆脱temp,只有vec.add(Integer.parseInt(str[i]));

答案 3 :(得分:0)

你可以这样做

String[] strArr = "12,65,21,23,89,67,12".split(",");
int[] intArr = new int[strArr.length];

for (int i = 0; i < strArr.length; i++) {
    intArr[i] = Integer.parseInt(strArr[i]);
}

Ints.max(intArr); // 89, with Google Guava Ints.max