【问题标题】:How do I provide null to BufferedReader's readLine() method using Eclipse如何使用 Eclipse 为 BufferedReader 的 readLine() 方法提供 null
【发布时间】:2015-10-28 10:34:43
【问题描述】:
public static void main(String[] args) {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        int charCount = 0;
        int wordCount = 0;
        int lineCount = 0;

        String line;
        try {
            while( (line = in.readLine()) != null ) {
                System.out.println(line);
                lineCount++;
                charCount += line.length();
                String[] words = line.split("\\W");
                wordCount += words.length;
            }
            System.out.println("charCount = " + charCount);
            System.out.println("wordCount = " + wordCount);
            System.out.println("lineCount = " + lineCount);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

直截了当:如何退出上述while循环?我读过另一个问题,readLine() 在没有更多要读取的行时返回 null,但是如何使用 Eclipse 的控制台来做到这一点?

我可以设法打破循环的唯一方法是添加案例,例如

if(line.length() == 2 || line.equals("exit")))
  break;

【问题讨论】:

  • 你试过ctrl-Z还是ctrl-D?
  • 您也可以使用 Scanner 类从 Eclipse IDE 读取输入。
  • 我必须纠正自己。它似乎不起作用。之前它可能退出了,因为我输入了一个长度为 2 的字符串。
  • @Ankit 我知道,我通常使用扫描仪。但是我必须研究java的IO类,因为我还没有。所以我比较想知道能不能写出这样的代码。
  • 您是否在控制台窗格处于焦点时尝试它?而且你是在按回车键输入之前的数据后才这样做的吗?

标签: java null bufferedreader readline


【解决方案1】:

如果你只想读一行,为什么需要while循环? 或者,如果您希望采用多个输入,那么您应该在第一个 readline() 中指定要采用多少输入; 否则我希望下面的代码能解决你的问题:)

公共类 TestRandomArray {

public static void main(String[] args) {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    int charCount = 0;
    int wordCount = 0;
    int lineCount = 0;

          try {
            String line = in.readLine();
            lineCount++;
            charCount += line.length();
            String[] words = line.split(" ");
            wordCount += words.length;
            System.out.println("charCount = " + charCount);
            System.out.println("wordCount = " + wordCount);
            System.out.println("lineCount = " + lineCount);
         in.close();
              } catch (IOException e) {
        e.printStackTrace();
    }
}

}

【讨论】:

  • 嘿,完全忘了回复你的答案,对不起。好吧,我不想只输入一行。我想知道如何使用 Eclipse 的命令行将“null”传递给 readLine()。
猜你喜欢
  • 2016-01-08
  • 1970-01-01
  • 2016-01-03
  • 2014-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多