4

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

BufferedReader br = new BufferedReader(System.in);
String filename = br.readLine();
Tim Bender
  • 20,112
  • 2
  • 49
  • 58
dawnoflife
  • 1,572
  • 10
  • 42
  • 62

2 Answers2

9

A BufferedReader is a decorator that decorates another reader. An InputStream isn't a a reader. You need an InputStreamReader first.

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

In response to your comment, here's the 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 handle this appropriately you need to either place the method call in a try/catch block or declare that it can be thrown.

An example of using a 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 the exception may be thrown:

void someMethod() throws IOException {
    BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
    String filename = br.readLine();
}
Tim Bender
  • 20,112
  • 2
  • 49
  • 58
corsiKa
  • 81,495
  • 25
  • 153
  • 204
  • do i need to give an exception for readLine()? it gives me an error if i don't – dawnoflife Feb 23 '11 at 03:09
  • I edited my answer with the documentation. Yes you need to handle the chance of an exception. Your error message on compile probably says "Must be caught or thrown." This means you can either catch it in a try catch, or declare the method to throw IOException. – corsiKa Feb 23 '11 at 03:11
  • I edited the question. i get the error with the scanner declaration now.it says variable (filename) not found. – dawnoflife Feb 23 '11 at 03:19
1

For what you are trying to do, I would recommend utilizing the Java.util.Scanner class. Pretty easy for reading input from the console.

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
}

Here is the documentation link http://download.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html

Matthew Cox
  • 13,566
  • 9
  • 54
  • 72
  • can't use scanner as I have another scanner after this and when i try to run a pre-determined input via script it just goes nuts. see edited quesiton – dawnoflife Feb 23 '11 at 03:20