Question

I'm relatively new to Java, so I'm just trying to get some practice with simple IO, as well as exception handling. My program is pretty basic - I just want to read a number from a file, and then convert it from Celsius to Fahreinheit, and output it on another file. The errors I'm getting are: "br/bw cannot be resolved" and "br/bw cannot be resolved to a variable." Seems like a scope issue, but I'm not sure. I say this because they are all occurring after I create the BufferedReader/BufferedWriter objects/variables.

Thanks for looking.

import java.io.*;
import java.util.*;

public class InputOutputTest {

    public static void main (String [] args){

        String dataIn = "input.txt";
        String dataOut = "output.txt";

        try{
            BufferedReader br = new BufferedReader( new FileReader( dataIn ) );
        }

        catch(FileNotFoundException e){
            System.out.println("Cannot open " + dataIn);

        }

        try{
            BufferedWriter bw = new BufferedWriter(new FileWriter(dataOut));
        }

        catch(IOException e){
            System.out.println("Cannot open " + dataOut);
        }

        Scanner fileIn = new Scanner( br );

        try{
            while(fileIn.hasNext()){

                int cTemp = fileIn.nextInt();
                int fTemp = cTemp * (9/5) + 32;

                bw.write("The temperature " + cTemp + " in fahrenheit is " + fTemp);
            }
        }

        catch(IOException e){
            System.out.println("Error, problem writing to file.");
        }

        try{
            br.close();
            bw.close();
        }
        catch(IOException e){System.out.println("Error: Problem closing input or output file.");}
    }
}
Was it helpful?

Solution

Because you've declared your br variable inside the try block, its scope is limited to that block.

To increase br's scope, declare it before the try block.

BufferedReader br = null;
try{
    br = new BufferedReader( new FileReader( dataIn ) );
}

You'll have to initialize it to null so you can be sure that it's always initialized to something (even null) before it's referenced for the first time.

Future references will need to check if it's null before using it.

OTHER TIPS

It's because you declared BufferedReader within a try block, it is not visible outside of this block. In Java, scope resolution (determined by enclosing curly braces) determines the visibility of an object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top