我在下面的代码中遇到这个问题,因为它没有运行但生成了空指针异常。我在这里想做的是获取一个字符串数组的输入,然后将其吐出但逗号,然后将其传递给整数类型,然后将其存储在 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/