Java error “Value of local variable is not used”

后端 未结 7 1301
温柔的废话
温柔的废话 2020-12-06 18:00

I am really new to java (started learning 2 days ago). Sorry if this is a stupid question. I am trying to learn how to use rt.exec & similar methods so I tried to make a

7条回答
  •  失恋的感觉
    2020-12-06 18:49

    There is no such thing as a stupid qiestion(only misplaced ones, in the worst case).

    The "Editor does not contain a main type" refers to the fact that you have not defined a main method. All java programs require a main method, as such:

    public static void main(String [] args){
        
    }
    

    This is where you must place your code.

    The "Value not used" is just a warning; it tells you that your variable p only exists within the try-block. You can declare your p-variable before the try - that way, you can use it outside the try-scope(the scope of a variable refers to where it exists, in this case, only inside the try-block).

    If you want to use your p, this is what you're after:

    public class Main {
        public static void main(String[] args) {
            Process p;
            try {
                Runtime rt = Runtime.getRuntime();
                p = rt.exec("calc.exe");
            } catch(Exception exc) {/*handle exception*/}
        }
    }
    

    [EDIT]: Note that it is part of the java coding convention to use Capital letters for the first letter of a class, e.g. Main.java(not main.java)

提交回复
热议问题