【问题标题】:Read text file to arrayList and sort将文本文件读取到 arrayList 并排序
【发布时间】:2017-03-28 13:24:37
【问题描述】:

这是我的txt文件“Q.txt”的sn-p。

12.54778255173505 :      ^FinishedLine
15.416218875438748 :  
 ^FinishedLine
16.245508427720914 :  ^FinishedLine
9.595696051997852 :   &^FinishedLine
11.971100145959943 : ! '^FinishedLine
11.678678199807727 : " $^FinishedLine
14.905855346233682 : # %^FinishedLine
15.98343143372184 : $ "^FinishedLine
16.053542916378102 : % #^FinishedLine

我需要对包含双精度和字符串的文本文件“Q.txt”进行排序。 它已使用“:”分隔,并且在每个短语的末尾都有(“^FinishedLine”)。当我运行它时,它所出现的只是“NumberFormatException:空字符串”错误。

  public class Sorting {

      public static void sort() throws IOException {

        Scanner s = new Scanner(new File("Q.txt"));
        ArrayList<Qpair> set = new ArrayList<>();
        String line = "";
        while (s.hasNext()) {
          String[] parts = line.split(" : ");
          set.add(new Qpair(Double.parseDouble(parts[0]), parts[1]));
          s.useDelimiter("^FinishedLine");

        }


      s.close();

      System.out.println(set);

    }

    private static class Qpair{
      private double d;
      private String s;
      public Qpair(double d, String s){
        this.d = d;
        this.s = s;     
      }

      public double getDouble(){
        return d;
      }

      public String getString(){
        return s;
      }

    }

    private static class QpairCompare implements Comparator<Qpair>{
      public int compare(Qpair x, Qpair y){
        return (int) (x.getDouble() - y.getDouble());

      }
    }

  }

【问题讨论】:

标签: java parsing arraylist split java.util.scanner


【解决方案1】:

据我所知:您将line 设置为空字符串。您进入while 循环而不更改line。您将这个空字符串拆分为:。我承认我必须尝试一下才能确定:它产生一个包含 1 个元素的数组,一个空字符串。您尝试将数组中的这个空字符串解析为双精度。

你告诉我们你得到了NumberFormatException: empty string。听起来我很同意。

我希望您能弄清楚缺少哪些代码行以及应该将其插入到哪里?

【讨论】:

    猜你喜欢
    • 2019-04-12
    • 1970-01-01
    • 2013-02-23
    • 2019-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-26
    • 1970-01-01
    相关资源
    最近更新 更多