【问题标题】:Is there a way of writing and reading two linked lists from a single text file in Java?有没有办法从 Java 中的单个文本文件中写入和读取两个链表?
【发布时间】:2017-05-15 03:12:49
【问题描述】:

我正在用 java 编写一个程序,其中涉及保存用户名和他们的高分。分数将保存在偶数行上,名字保存在奇数行上。例如:

Horace
2203
Rufus
435
Bertie
4725
Lawrence
174
Kane
...

这可能吗?是否需要导入任何库?文本文件是否需要在 Eclipse 中的项目内部?

非常感谢。

到目前为止,我已经创建了两个列表:

LinkedList<String> listName = new LinkedList<String>();
LinkedList<Integer> listScore = new LinkedList<Integer>();

并将数据保存给他们:

listName.add(answer);
listScore.add(score);

【问题讨论】:

  • 是的,只需阅读这些行并将它们交替添加到不同的列表中。写作时,反其道而行之。你尝试过什么代码?
  • 这可能是一个开始的地方:Files.readAllLines
  • @markspace 到目前为止,我只尝试创建两个列表,然后将名称和分数添加到所述列表中。
  • 分享你的代码,我们就能理解问题所在

标签: java input import output writing


【解决方案1】:

这是可能的,但从概念上讲:这是错误的方法。

你看,你所拥有的信息属于在一起。我猜你想创造

A)List&lt;String&gt; players

B)List&lt;Integer&gt; scores

例如。

然后“相同的索引”意味着:玩家 X 的得分

不要那样做。而是创建一个具有两个属性(名称和分数)的 Player 类;然后使用/填写List&lt;Player&gt;

但除了如何建模数据的问题之外;事情真的很简单:

open your file
loop:
  read one line --- which should contain a String (name)
  read one line --- which should contain a number

从伪代码中可以看出;那里真的没有魔法。您了解您的数据的结构;所以就用它吧!

【讨论】:

  • 啊,对,因为我想让迭代次数乘以 2 得到分数,乘以 2 减去 1 得到前一个包含名称的数字(奇数) 有点像并行数组系统
  • 对不起,我没有得到你的评论。不知道你想做什么。但请务必查看我所做的更新。
  • 哈哈哈,是的,我看到了 :) 取数字 7 和 8。7 -> 姓名,8-> 分数。 8/2(2 行的两个值)= 第四次迭代所以: for (int i = 0; i
  • 注释修改后的代码:so: for (int i = 0; i
【解决方案2】:

您可以使用以下方法:-
1) 逐行读取文件。
2)如果奇怪,假设它是用户,放入用户列表。
3)如果是偶数,假设是score,放入score list。
4) 使用链表维护顺序,因此两个列表中的任何索引都将保存相关数据。

您可以在以下示例的基础上进行构建-

public static void main(String[] args){
        //input.txt file is kept at the same place as that of class ReadFile
        File file=new File(ReadFile.class.getResource("input.txt").getFile());
        //User List
        List<String> userList=new LinkedList<String>();
        //Score List
        List<String> scoreList=new LinkedList<String>();
        int count =1;
        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            String sCurrentLine;
            while ((sCurrentLine = br.readLine()) != null) {
                if(count%2==0){
                    //Line is even
                    scoreList.add(sCurrentLine);
                }else{
                    //Line is odd
                    userList.add(sCurrentLine);
                }
                count++;
            }
        System.out.println("Printing User List:"+userList+"\n\nPrinting Score List:"+scoreList);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-07
    • 2021-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多