java - 要放入 Vector 的字符串数组

标签 java

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

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");



}

}

最佳答案

您必须创建一个数组。替换

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);
}

关于java - 要放入 Vector 的字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6147981/

相关文章:

java - 如何使用多线程使用Camel File Component Consumer

java - 从 Callable 返回的本地类的序列化

java - 从ObjectName获取Google云存储文件

java - 从属性读取数据而不解析 Unicode 字符

java - 咖啡因缓存 - 许多键到单个值

java - 运行所有类并使用 Maven 提取信息

java - 我怎样才能打乱一个单词的字母?

java - Javascript 中的 URL 解码

java - 无法导入 Google Analytics

java - 将特定格式的多个输入作为 java 中的单个输入