如何在列表中分割字符串并将逗号用作定界符

时间:2019-01-30 19:51:46

标签: java

所以我正在读取csv格式的文件,然后对其进行格式化并将其输出到控制台,我唯一的问题是它可以正常工作,直到我击中有空格的字符串,所以我想知道是否有办法读取数据到列表中,并在有逗号的情况下使元素递增 所以如果我有这个文本文件正在阅读

000001,松树,长底叶,600.0 000002,伦巴斯,精灵之路面包,200.0 000003,葡萄酒,林地精灵酒,400.0 000004,蘑菇,农夫最优秀,125.0 000005,秘银,矮人化装甲,3000.0

如果这样做的话,我怎么会把长底叶子当作一个字符串?因为这是香港专业教育学院的尝试

import java.io.*;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileSystemView;
import java.util.ArrayList;
import java.util.Scanner;

public class ProductReader {
    public static void main (String[] args) {
        ArrayList<String> reader = new ArrayList<String>();
        JFileChooser file = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
        int returnValue = file.showOpenDialog(null);
        int line = 0;
        int end = 0;
        int counterID = 0;
        int counterProduct = 1;
        int counterDescription = 2;
        int counterCost = 3;

        if (returnValue == JFileChooser.APPROVE_OPTION) {
            File selectedFile = file.getSelectedFile();
            String fileName = selectedFile.getName();

            try {
                Scanner fin = new Scanner (selectedFile);

                while (fin.hasNext()) {
                        String data = fin.next();
                        reader.add (data.replace(",", ""));
                }
                fin.close();
            }
            catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }

        System.out.printf ("%s", "ID#");
        System.out.printf ("%15s", "Product");
        System.out.printf ("%15s", "Description");
        System.out.printf ("%15s", "Cost\n");
        System.out.print ("==============================================================\n");

        for (int x = 0; x < reader.size(); x++) { 
            if (line == 0) {
                System.out.printf ("%-9s", reader.get(counterID));
                counterID += 4;
            }

            if (line == 1) {
                System.out.printf ("%-16s", reader.get(counterProduct));
                counterProduct += 4;
            }

            if (line == 2) {
                System.out.printf ("%-18s", reader.get(counterDescription));
                counterDescription += 4;
            }

            if (line == 3) {
                System.out.print (reader.get(counterCost));
                counterCost += 4;
            }

            end++;

            if (reader.size() > end) {
                line++;
            }

            if (line == 4) {
                System.out.println();
                line = 0;
            }
        }
    }
}

0 个答案:

没有答案