为什么不将CSV文件中的每个元素都添加到字符串中?

时间:2019-10-21 23:15:00

标签: file csv parsing input

package edu.nyu.cs.jg6155;

import java.util.Arrays;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
//Data/CSV file used: https://data.cityofnewyork.us/Education/2016-Public-Data-File-Teacher/w9if-3pyn


    public class main {
         public static void main(String[] args) throws FileNotFoundException {
          //filereader will spit out each thing in the csv separated by commas instead of whitespace
          Scanner fileReader = new Scanner(new File("src/pupiltoteacher.csv")).useDelimiter(",");

          //Appends each element of the file to a string
          String filetext = "";
          int f = 0;
          while(fileReader.hasNext()) {
             filetext += fileReader.next() + ",";
          }
          //creates a string array of the file elements
          String[] file = filetext.split(",");

          //creates a 2D array where 2darr[x][0] is the first element of each line
          //z is the number of columns in the data
          int z = 3;
          String[][] fileInfo = new String[file.length/z][z];

          //adds each element of the file to the 2D array 
          int count = 0;
          for(int i = 0; i < file.length/z; i++) {
              for(int j = 0; j < z; j++)    {
                  fileInfo[i][j] = file[count];
                  count++;
                  System.out.print(fileInfo[i][j] + " ");
              }
             System.out.println();
          }
      }

我的代码在解析文件时并未将每个元素都添加到字符串中,应该有4569,但是在删除学校名称中的任何逗号后只有〜3045。 CSV文件中的第一个和最后一个元素与字符串匹配,我不知道出了什么问题。

注意:我们不允许使用任何CSV解析库,而必须使用扫描仪。

0 个答案:

没有答案