Buffered Reader and Scanner

I want to know what's wrong with that. it gives me a constructor error (java.io.InputSream)

BufferedReader br = new BufferedReader(System.in);
String filename = br.readLine();
+3
source share
2 answers

BufferedReader is a decorator that decorates another reader. InputStream is not a reader. First you need an InputStreamReader.

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

In response to your comment here's javadoc for readline:

Readline

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

To deal with this, you need to either put the method call in a try / catch block or declare that it can be thrown.

An example of using the try / catch block:

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

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

An example of declaring that an exception can be thrown:

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

For what you are trying to do, I would recommend using the Java.util.Scanner class. Pretty easy to read console input.

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

+2

Source: https://habr.com/ru/post/1794033/


All Articles