0

我有一个程序可以在我的项目文件夹中打开一个 .txt 文件并读取其中的行。我知道文件读取有效,所以它不是 I/O 问题(或摆动,因为我也在使用它)但是当我设置 nim(我的变量)=anArray[num](也是一个变量)时它没有工作。注意:当我运行程序时,它会到达 println("First Declaration") 所以它只是数组的设置不起作用。谢谢 :)

import java.io.File;
import java.util.Scanner;

import javax.swing.JFrame;


public class SpanishSetOne extends JFrame {

    private static Scanner s;
    public String[] anArray;
    public String nim;

    public SpanishSetOne() {
        super("Spanish Set 1");

        initFile("spanish");
        setSize(500,500);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public void initFile(String name) {
        try{
            s = new Scanner(new File(name + ".txt"));
            System.out.println("setScanner");
        }catch(Exception e) {
            System.out.println("ERROR - Could not read file");
        }
        int num = 0;
        while(s.hasNext()) {
            System.out.println(("Made it into the loop"));
            nim = s.nextLine();
            System.out.println("First declaration");
            anArray[num] = nim;
            System.out.println(anArray[num]);
            num++;
        }
    }
}
4

3 回答 3

2

你需要像这样初始化你的数组:

String[] array = new String[10];

我也会考虑使用 ArrayList 这样您就不必担心数组的大小

于 2013-08-20T15:37:51.700 回答
0

您尚未初始化数组。 public String[] anArray;它是一个字符串数组,分配了零个内存位置来存储任何字符串。

Use String[] anArray = new String[numberOfElements]; 
// Here anArray will be a String Array with 'numberOfElements' memory location.

强烈推荐使用

List<String> anArrayList = new ArrayList<String>();

希望这可以帮助。

于 2013-08-20T15:35:47.860 回答
0

您必须先初始化数组,然后才能使用它。

anArray = new String[count];
//count being the number of elements you want to store in the array
于 2013-08-20T15:35:57.657 回答