Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java error "Value of local variable is not used"

Tags:

java

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 very simple program which runs calc.exe. This is the code:

public class main {
{
try {
Runtime rt = Runtime.getRuntime() ;
Process p = rt.exec("calc.exe") ;
 }

catch(Exception exc){/*handle exception*/}
    }
}

http://i.stack.imgur.com/KrpsT.png

I get the error " The value of local variable p is not used".

And if I try to compile this is what I get:

http://i.stack.imgur.com/Ryllw.pngI

I think it's easy to fix but I don't know how. Would be nice if someone helped.

like image 910
Andrew Howard Avatar asked Jun 16 '12 11:06

Andrew Howard


3 Answers

Well, the error "The value of local variable p is not used.", Is not actually an error. It's your IDE (Eclipse), warning you that you aren't actually reading that variable, so you aren't receiving any input from it.

And the other problem with your class is, you don't have a main method. Like this,

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

And by the way, you should always start a class name with a captial letter. So public class main, should actually be public class Main

like image 86
Austin Avatar answered Oct 15 '22 22:10

Austin


You get that error because you don't have the main method that is used to start the java program:

public class main {

public static void main(String[] args) {
   try {
       Runtime rt = Runtime.getRuntime() ;
       Process p = rt.exec("calc.exe") ; // here, eclipse is WARINING(so you can ignore it) you that that the variable p is never used(it's just a warning)
   } catch(Exception exc) {
       /*handle exception*/
       // never do this, always put at least a System.out.println("some error here" + e); so you don't ignore a potential exception
   }
}
like image 39
user Avatar answered Oct 15 '22 23:10

user


I believe what you have is not an error but a warning; eclipse (and other IDEs/compilers) will tell you that, although you assigned a value to the variable p, you did not use it anywhere. It tells you this because this is sometimes an error; mostly when you assign a value to a variable, you later use that variable in some way.

You can eliminate the error by changing that particular statement to just

rt.exec("calc.exe")

since you are not required to assign a value from the call to exec.

like image 40
arcy Avatar answered Oct 15 '22 23:10

arcy