我正在尝试将CS​​V文件读入ArrayList或String [] []数组。在这种情况下,我试图将其读取到列表中,然后使用标记器将列表形成数组。 csv文件有7列(A-G)和961行(1-961)。我的2D数组for循环不断返回空指针,但我认为它应该可以工作。

public class FoodFacts
{
    private static BufferedReader textIn;
    private static BufferedReader foodFacts;
            static int numberOfLines = 0;
            static String [][] foodArray;
    public static String  aFact;
    static  int NUM_COL = 7;
    static int NUM_ROW = 961;
    // Make a random number to pull a line
    static Random r = new Random();

    public static void main(String[] args)
    {
        try
        {
            textIn = new BufferedReader(new InputStreamReader(System.in));
            foodFacts= new BufferedReader(new FileReader("foodfacts.csv"));
            Scanner factFile = new Scanner(foodFacts);
            List<String> facts = new ArrayList<String>();

            String fact;
            System.out.println("Please type in the food you wish to know about.");
            String request = textIn.readLine();
            while ( factFile.hasNextLine()){
                fact = factFile.nextLine();
                StringTokenizer st2 = new StringTokenizer(fact, ",");
                //facts.add(fact);
                numberOfLines++;
                while (st2.hasMoreElements()){
                    for ( int j = 0; j < NUM_COL ; j++) {
                        for (int i = 0; i < NUM_ROW ; i++){
                            foodArray [j][i]= st2.nextToken();  //NULL POINTER HERE
                            System.out.println(foodArray[j][i]);
                        }
                    }
                }
            }
        }
        catch (IOException e)
        {
            System.out.println ("Error, problem reading text file!");
            e.printStackTrace();
        }
     }
 }

最佳答案

在使用之前,将foodArray初始化为foodArray = new String[NUM_ROW][NUM_COL];

另外,一次读取一行时不需要内部for循环。

使用numberOfLines作为行:

        while ( factFile.hasNextLine() && numberOfLines < NUM_ROW){
                 fact = input.nextLine();
                 StringTokenizer st2 = new StringTokenizer(fact, ",")    ;
                 //facts.add(fact);
                while (st2.hasMoreElements()){
                  for ( int j = 0; j < NUM_COL ; j++) {
                    foodArray [numberOfLines][j]= st2.nextToken();
                    System.out.println(foodArray[numberOfLines][i]);
                 }
                }
                 numberOfLines++;
            }


或者,我认为您可以使用split一次获取所有列,例如

        while ( factFile.hasNextLine() && numberOfLines < NUM_ROW){
           fact = input.nextLine();
           foodArray [numberOfLines++] = fact.split(",");
        }


一个问题:将所有变量声明为静态类变量是否有特定目的?它们中的大多数适合作为方法内的局部变量,例如numberOfLines

10-06 06:47