我想知道为什么我的Java程序在我的控制台上工作:
javac Main.java
java Main
...而不是在Eclipse中,因为我有这个错误:
线程“main”java.lang.NullPointerException中的异常 在codePin.main.main(main.java:48) - > char passwordArray [] = console.readPassword(“输入pin:”);
这是我的代码:
package codePin;
import java.io.*;
import java.util.*;
public class main {
static public boolean readPinsData(File dataFile, ArrayList<Integer> data) {
boolean err = false;
try {
Scanner scanner = new Scanner(dataFile);
String line;
while (scanner.hasNext()) {
line = scanner.nextLine();
try {
data.add(Integer.parseInt(line));
} catch (NumberFormatException e) {
e.printStackTrace();
err = true;
}
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
err = true;
}
return err;
}
public static void main(String[] args) {
System.out.println("-----------------------");
System.out.println("APPLICATIONS BESOINS");
System.out.println("-----------------------");
Console console = System.console();
System.out.println(console == null);
int pinSize = 0;
int nbTry = 0;
boolean authenticated = false;
do {
do {
char passwordArray[] = console.readPassword("Enter pin: "); //This is the line causing the error
pinSize = passwordArray.length;
if (pinSize != 4) {
System.out.println("Pin must be 4 digits");
} else {
System.out.println("Checking...");
}
ArrayList<Integer> pins = new ArrayList<Integer>();
readPinsData(new File("bdd.txt"), pins);
String[] thePins = new String[pins.size()];
for (int i = 0; i < thePins.length; i++) {
thePins[i] = pins.get(i).toString();
}
String passEntered = String.valueOf(passwordArray);
for (int i = 0; i < thePins.length; i++) {
if (passEntered.equals(thePins[i]) && pinSize == 4) {
System.out.println(":)");
authenticated = true;
break;
}
}
} while (pinSize != 4);
if (!authenticated && pinSize == 4) {
System.out.println(":(");
nbTry++;
}
} while (nbTry < 3 && !authenticated);
}
}
正如您所看到的,我在我的public static void main方法的开头添加System.out.println(console == null);
只是为了检查,它确实在控制台中返回true。
所以我的问题是:如何在Eclipse中初始化控制台,以便我的代码可以工作? 谢谢
答案 0 :(得分:4)
这是因为System.console()
将返回与当前Java虚拟机关联的唯一Console对象(如果有),而eclipse没有唯一的控制台。
您应该尝试使用Scanner
或System.in
来获取控制台输入