【发布时间】:2014-03-21 21:09:57
【问题描述】:
我的问题是,为什么我在线程“main”java.lang.ArrayStoreException 中得到一个异常:
在 java.lang.System.arraycopy (本机方法) 在 java.util.ArrayList.toArray(未知来源) 在 Main.main (Main.java:50)
这是我的代码:
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);
}
}
我的 bdd.txt 文件看起来像:
1111
2222
3333
4444
5555
6666
7777
8888
9999
【问题讨论】:
-
另一个问题是您将字符串与
==进行比较。使用 equals() 代替。并使用集合而不是数组。没有理由将列表转换为数组:您可以直接迭代列表。 -
我看不到如何使用集合。你是什么意思 ?我需要 List 的大小来循环它,对吗?
-
ArrayList 是一个集合。您可以遍历 ArrayList。无需将列表转换为数组即可对其进行迭代。查看您的代码:它从文件中读取字符串,然后将每个字符串转换为整数并将整数存储在列表中,然后将整数列表转换为字符串数组。为什么不将这些行读入字符串列表,并使用 list.contains(passEntered) 检查列表是否包含输入的密码?所有这些转变的意义何在?
-
我明白了,实际上我在代码上花了几个小时,但我没有意识到这不是更好的方法。我有点失落。
标签: java