【问题标题】:Why do I get an ArrayStoreException in Java?为什么在 Java 中会出现 ArrayStoreException?
【发布时间】: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


【解决方案1】:

基本上你有一个List&lt;Integer&gt; 并且你试图将它的内容存储在一个String[] 中。你不能那样做。如果您想将每个 Integer 转换为 String,则需要明确地执行此操作。

例如:

String[] thePins = new String[pins.size()];
for (int i = 0; i < thePins.length; i++) {
    thePins[i] = pins.get(i).toString();
}

或者构建一个List&lt;String&gt;,而不是使用一个数组。

或者根本不用费心将所有内容都转换为字符串集合 - 相反,只需遍历 pins 并以这种方式进行测试。

如 JB Nizet 所述,you should also use equals rather than == when comparing strings

【讨论】:

  • 我试图以这种方式转换它“String[] thePins = pins.toArray(new String[pins.size()]);”。我需要循环每个引脚的 Integer 吗?
  • @FlorentP:是的,我们可以看到你试图做什么,因为这是问题所在:) 你不能这样做——你需要遍历整数并在每个整数上调用 toString() .
  • 但是如何在 List 上做循环呢? List.size() 显然不起作用。
  • @FlorentP:是的,List.size() 非常肯定确实有效。我将编辑我的答案以展示您如何做到这一点。
  • 另外,我如何修改代码的结尾,只打印一个:) 或:((取决于人输入的密码)。我有点困惑
最近更新 更多