【问题标题】:buffered reader and scanner缓冲阅读器和扫描仪
【发布时间】:2011-02-23 02:59:58
【问题描述】:

我想知道这有什么问题。它给了我一个构造函数错误(java.io.InputSream)

BufferedReader br = new BufferedReader(System.in);
String filename = br.readLine();

【问题讨论】:

  • 回滚编辑,因为问题不再有意义。

标签: java


【解决方案1】:

BufferedReader 是装饰另一个阅读器的装饰器。 InputStream 不是阅读器。您首先需要一个 InputStreamReader。

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

针对您的评论,这里是 readline 的 javadoc:

读取线

public String readLine()
                throws IOException

    Read a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

    Returns:
        A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached 
    Throws:
        IOException - If an I/O error occurs

要适当地处理这个问题,您需要将方法调用放在 try/catch 块中,或者声明它可以被抛出。

使用 try/catch 块的示例:

BufferedReader br = new BufferedReader (new InputStreamReader(System.in));

try{
    String filename = br.readLine();
} catch (IOException ioe) {
    System.out.println("IO error");
    System.exit(1);
} 

声明可能抛出异常的例子:

void someMethod() throws IOException {
    BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
    String filename = br.readLine();
}

【讨论】:

  • 我需要给 readLine() 一个例外吗?如果我不这样做,它会给我一个错误
  • 我用文档编辑了我的答案。是的,您需要处理出现异常的机会。您在编译时的错误消息可能是“必须被捕获或抛出”。这意味着您可以在 try catch 中捕获它,或者声明抛出 IOException 的方法。
  • 我编辑了这个问题。我现在收到扫描仪声明的错误。它说找不到变量(文件名)。
【解决方案2】:

对于您想要做的事情,我建议您使用 Java.util.Scanner 类。从控制台读取输入非常容易。

import java.util.Scanner;
public void MyMethod()
{
    Scanner scan = new Scanner(System.in);

    String str = scan.next();
    int intVal = scan.nextInt();
    double dblVal = scan.nextDouble();  
    // you get the idea
}

这里是文档链接http://download.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html

【讨论】:

  • 无法使用扫描仪,因为在此之后我有另一个扫描仪,当我尝试通过脚本运行预先确定的输入时,它只会发疯。查看已编辑的问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-17
  • 1970-01-01
  • 1970-01-01
  • 2013-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多