My question is, why do I get an Exception in thread "main" java.lang.ArrayStoreException :
at java.lang.System.arraycopy (native method) at java.util.ArrayList.toArray (unknown source) at Main.main (Main.java:50)
Here's my code :
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) {
Console console = System.console();
int pinSize = 0;
do{
char passwordArray[] = console.readPassword("Enter pin: ");
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);
//System.out.println(pins);
//System.out.println(passwordArray);
String[] thePins = pins.toArray(new String[pins.size()]);
String passEntered = String.valueOf(passwordArray);
int i = 0;
for(i = 0 ; i < thePins.length ; i++){
if(passEntered == thePins[i]){
System.out.println(":)");
}else{
System.out.println(":(");
}
}
}while(pinSize != 4);
}
}
My bdd.txt file looks like :
1111
2222
3333
4444
5555
6666
7777
8888
9999
Basically you've got a List<Integer>
and you're trying to store the contents of it in a String[]
. You can't do that. If you want to convert each Integer
into a String
, you'll need to do that explicitly.
For example:
String[] thePins = new String[pins.size()];
for (int i = 0; i < thePins.length; i++) {
thePins[i] = pins.get(i).toString();
}
Or build a List<String>
instead of using an array.
Or don't bother converting everything to a string collection at all - instead, just iterate over pins
and test that way.
As noted by JB Nizet, you should also use equals
rather than ==
when comparing strings.
See more on this question at Stackoverflow