我不确定为什么在包含 while
循环的行上收到 NullPointerException
。
最初是在创建String[] 输入
时。它充满了 null
所以也许这就是我收到错误的原因。我尝试通过添加这段代码来解决这个问题:
for (String k : input) {
k = "empty";
}
这可能是错误的方法,所以我仍然收到错误。
代码:
String[] input = new String[3];
while(!input[0].equals("exit")) {
Scanner sc = new Scanner(System.in);
input = sc.nextLine().split(" ", 3);
switch(input[0]) {
// vi
case "vi":
System.out.println("hi");
break;
// ls
case "ls":
break;
// mkdir
case "mkdir":
break;
// pwd
case "pwd":
break;
}
}
最佳答案
这个
for (String k : input) {
k = "empty";
}
实际上相当于
for (int i = 0; i < input.length; i++) {
String k = input[i];
k = "empty";
}
更改引用k
不会影响数组中的引用。
就这么做
for (int i = 0; i < input.length; i++) {
input[i] = "empty";
}
我不确定您的 while
循环的用途,因此我不会对此发表评论。
关于java - String[] 中的空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22445631/