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.");}
    }
}
有帮助吗?

解决方案

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.

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top