要放入Vector的字符串数组

Spl*_*ter 0 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");



}

}
Run Code Online (Sandbox Code Playgroud)

And*_*s_D 5

你必须创建一个数组.更换

temp = null;
Run Code Online (Sandbox Code Playgroud)

temp = new int[str.length];
Run Code Online (Sandbox Code Playgroud)

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

if (input == null) {
   // return or throw exception
}
Run Code Online (Sandbox Code Playgroud)

在你的方法的开头.


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

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);
}
Run Code Online (Sandbox Code Playgroud)