有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

解析如何在Java中将文本解析为列表?

我将以下文件另存为.txt

I Did It Your Way, 11.95
The History of Scotland, 14.50
Learn Calculus in One Day, 29.95
Feel the Stress, 18.50
Great Poems, 12.95
Europe on a Shoestring, 10.95
The Life of Mozart, 14.50

我需要用Java在不同的JList上显示书名和价格。我该怎么做

另外,如果我有一个具有两个值的数组(一旦我将标题与价格分开),我如何将标题和价格复制到各自的数组中


共 (2) 个答案

  1. # 1 楼答案

    如果值以逗号分隔,则可以使用http://opencsv.sourceforge.net/。这是示例代码

                CSVReader reader = new CSVReader(new FileReader("test.txt"));
        List myEntries = reader.readAll();
    
        int noOfEntries=myEntries.size();
    
        String[] titles=new String[noOfEntries]; 
        String[] price=new String[noOfEntries]; 
    
        String[] entry=null;
        int i=0;
        for(Object entryObject:myEntries){
            entry=(String[]) entryObject;
            titles[i]=entry[0];
            price[i]=entry[1];
            i++;
                }
    
  2. # 2 楼答案

    看起来很简单,你不需要任何花哨的东西

    BufferedReader r = new BufferedReader(new FileReader("file.txt"));
    List<String> titles = new ArrayList<String>();
    List<Double> prices = new ArrayList<Double>();
    
    while ((String line = r.readLine()) != null) {
      String[] tokens = line.split(",");
      titles.add(tokens[0].trim());
      prices.add(Double.parseDouble(tokens[1].trim()));
    }
    
    r.close();