【问题标题】:Add data from file into ArrayList and sorting将文件中的数据添加到 ArrayList 并排序
【发布时间】:2015-01-08 15:10:07
【问题描述】:

我正在尝试将包含字符串和整数的文本文件中的数据放入 ArrayList,然后对其进行排序(这将取决于整数值)。

文件模式中的文本类似于“Höllviken;23642”。用“;”隔开特点。

到目前为止,我已经得到了这个:

public class SorteraOrter{
    public static void main(String[] args)throws IOException{

    // scans file orter
    File stad = new File("C:\\Users\\Johan\\Desktop\\orter.txt");
    Scanner n = new Scanner(stad);


    ArrayList<Object> city = new ArrayList();

    while(n.hasNext()){
        String ln = n.nextLine();
        String[] arr = ln.split(";");
        Ort ort = new Ort(arr[0],Integer.valueOf(arr[1]));
        city.add(ort);
    }
    System.out.println(city.toString());

    }
}

对于排序,我已经声明了一些方法并创建了一个 compareTo 方法来与排序一起使用。 :

package soter_orter;

public class Ort implements Comparable<Ort> {

    // fields
    private int postnr = 0;
    private String ort = "";

    // constructor 
    public Ort(String s, int p){s = ort; p = postnr;}

    // method names
    public int postnr() {
        return postnr;
    }

    public String ort() {
        return ort;
    }

    public int compareTo(Ort o){
        return o.postnr - postnr;
    }

    public String toString(){
        return ort + " " + postnr;
    }
}

所以首先我必须成功地将这些字符串和整数添加到我的 ArrayList 中。我还需要以某种方式将它们连接起来,因为数字和文本文件属于彼此。

我当前的问题是尝试将文件输入移动到 ArrayList 后得到的输出 -

[ 0, 0, 0, 0, 0, 0, 0]

我更进一步,将 ArrayList 的元素添加到对象数组中。我可以对此进行排序,但无法使用我的 toString 方法查看它。

    Object[] arr = new Object[city.size()];

for (int i = 0; i<city.size(); i++){
    arr[i] = city.get(i);
}

Arrays.sort(arr);
for (Ort o : arr){

}

我无法在 for 循环中打印此内容。我收到消息:“类型不匹配:无法从元素类型 Object 转换为 Ort”

所以,到目前为止,我无法打印 ArrayList 和 Object Array。

【问题讨论】:

  • 这个问题没有理由被负面标记

标签: java sorting arraylist io


【解决方案1】:

你在 Ort 类中的构造函数应该是

public Ort(String s, int p){ort=s;  postnr=p;}

【讨论】:

    【解决方案2】:

    你的构造函数错了。

    替换

    public Ort(String s, int p){s = ort; p = postnr;}
    

    public Ort(String s, int p){ort = s; postnr = p;}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-10
      • 1970-01-01
      • 2021-04-08
      • 2015-12-09
      • 2011-10-13
      • 1970-01-01
      相关资源
      最近更新 更多