I wanted to know why does my Java program work in console when I do :
javac Main.java
java Main
...and not in Eclipse, as I have this error :
Exception in thread "main" java.lang.NullPointerException at codePin.main.main(main.java:48) --> char passwordArray[] = console.readPassword("Enter pin: ");
Here's my code :
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);
}
}
As you can see, I added System.out.println(console == null);
at the beggining of my public static void main method just to check, and it does actually return true in the console.
So my question is : how to initialize the console in Eclipse so my code could work ? Thank you