【问题标题】:In Java, how do I read two data types, char and int from a single .dat file?在 Java 中,如何从一个 .dat 文件中读取两种数据类型,char 和 int?
【发布时间】:2021-03-04 17:15:12
【问题描述】:

作为更大任务的一部分,我被指示读取用户输入的包含以下数据的 .date 文件路径。

e 2
b 1
a 3
h 5
c 4

通过链表函数运行后,列表应在控制台中显示为“海滩”。这是我正在努力的代码sn-p。

     do {

        Scanner scnr = new Scanner(System.in);
        System.out.print("Enter the secret file name: ");
        String filename = scnr.nextLine();
        File inputFile = new File(filename);
        Scanner reader = new Scanner(inputFile).useDelimiter("\\/");

        while (reader.hasNextLine()) {


            //String line = reader.nextLine();
            //int val = reader.readInt();
        }

        System.out.print("Ready to play? (no to quit): ");
        userDecision = scnr.nextLine();

    } while (!userDecision.equalsIgnoreCase("no"));

我认为最好将文件作为字符解析为字符串,但我不知道该怎么做。是的,我知道这是一个愚蠢的问题。

【问题讨论】:

  • 将其作为字符串读取,使用reader.next()。根据需要进行解析。
  • 为什么是.useDelimiter("\\/")?这不是显示文件中的分隔符 - 会 混淆 next()nextInt()

标签: java file parsing key-value-store


【解决方案1】:

正如 Andy 所写,next() 用于读取字符串,nextInt() 读取整数。

nextLine() 读取从当前位置到行尾的余数。在整数之后,余数是换行符,这解释了为什么您的尝试没有按预期工作。

【讨论】:

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