Variables cannot be resolved

前端 未结 3 1799
难免孤独
难免孤独 2021-01-21 15:07

I am making my first Java program (In hopes to master it in the next century) and have ran into some issues. When I try to create a string with a combination of text and previou

3条回答
  •  轮回少年
    2021-01-21 15:24

    In Java you can only use a variable in the block in which it's defined.

    You declare the variables data and input inside your try block.

    This means you can only use them inside that block.

    If you want to use data and input in step 2, you should declare them before your try block.


    To fix it, do something like this:

    public class Application {
    
        public static main(String[] args) {
    
            String data = null;
            String commandOutput = "";
            BufferedReader input = null;
    
            try {
                // do stuff
                data = text;
                input = // initialize buffered reader
                String line = input.readLine();
                while (line != null) {
                    commandOutput += line;
                    line = input.readLine();
                }
            }
            catch (SomeSpecificException ex) {
                // please handle exceptions!
            }
            catch (IOException ioex) {
                // handle IO Exceptions here
            }
            finally {               
                try {
                    input.close();
                }
                catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            .
            .
            .
            String emailBody = "blah blah " + data + " blah blah " + commandOutput;
        }
    }
    

提交回复
热议问题