有 Java 编程相关的问题?

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

readfile Java使用Enter键逐行显示文件

我正在尝试使用Enter键逐行显示文件,但是我尝试的if语句似乎不起作用。如果我忽略If语句,它会工作,但感觉不完整,因为我要求输入,而对它什么也不做

这就是我所拥有的:

import java.util.Scanner;
import java.io.*;
public class LineByLine  {
   public static void main(String[] args) throws IOException {
    Scanner in = new Scanner(System.in);
    System.out.println("What is the filename?");
    String input = in.nextLine();
    BufferedReader buff = new BufferedReader(new FileReader(input));
    String sen = buff.readLine();
    System.out.println(sen);
    Scanner enter = new Scanner(System.in);
    while (sen != null){
            String output = enter.next();
            if (output.equals("")){
                System.out.println(sen = buff.readLine());
            }
    }
   }
}

我只是不知道为什么我的if语句不起作用


共 (1) 个答案

  1. # 1 楼答案

    核心问题是您误解了Scanner及其默认配置:开箱即用,Scanner在任何数量的空白上拆分.next()请求下一个令牌;标记是出现在空白之间的东西

    因此,按enter键500次将生成标记。毕竟,标记是分隔符之间的内容,默认分隔符是“任意数量的空白”。按enter键一段时间仍然只是输入相同的分隔符

    潜在的问题是,大多数人似乎认为扫描仪一次只能读取一行。它不会那样做。完全但你想让它这么做。所以,告诉它!Easy peasy-让扫描仪做你认为它已经做了的事情:

    Scanner in = new Scanner(System.in);
    in.useDelimiter("\\R"); // a single enter press is now the separator.
    

    您还应该停止在扫描仪上使用nextLinenextLine和任何其他{}调用不能混合。解决这个问题最简单的方法是只使用nextLine,而不使用其他任何东西,,永远不要使用nextLine。通过上面的设置,.next()为您获取一个令牌,它是一整行——因此,不需要nextLine,这是个好消息,因为nextLine被破坏了(它做了规范说它应该做的,但它做的是违反直觉的。我们可以就“破坏”是否是对它的合理描述进行语义辩论。关键是,它没有做你认为它做的事情)

    另外,当你在做的时候,不要做多个扫描仪。而且,要改进此代码,必须正确关闭资源。你没那么做。让我们使用try with,这就是它的用途

    public static void main(String[] args) throws IOException {
      Scanner in = new Scanner(System.in);
      in.useDelimiter("\\R");
      System.out.println("What is the filename?");
      String input = in.next();
      try (BufferedReader buff = new BufferedReader(new FileReader(input))) {
        String sen = buff.readLine();
        System.out.println(sen);
        while (sen != null){
          enter.next(); // why does it matter _what_ they entered?
          // as long as they pressed it, we're good, right? Just ignore what it returns.
          System.out.println(sen = buff.readLine());
        }
      }
    }