I'm new to RMI and trying to apply the following to the project I'm working on.
Does this piece of code Naming.lookup...... theWork.newCalculator();
always need to be in main
method?
Can I call myCalculator
outside main
method?
When I tried, I'm getting myCalculator cannot be resolved
error.
Below example calls myCalculator
in main
so it works. How do I make myCalculator.plus(arg)
available in another method?
public static void main(String [] args)
{
try{
CalculatorFactory theWorks = (CalculatorFactory)Naming.lookup("rmi://localhost:13456/CalculationsAnon");
Calculator myCalculator = theWorks.newCalculator();
System.out.println("I have a calculator");
int val = 0;
myCalculator.clear();
BufferedReader bin = new BufferedReader(new InputStreamReader(System.in));
for(;;)
{
System.out.println(": "+val+":");
System.out.print("Command>");
String s = (bin.readLine().trim());
if(s.equals("+")){
System.out.print("Value>");
int arg = 0;
s=(bin.readLine().trim());
arg = Integer.parseInt(s);
val = myCalculator.plus(arg);
}
// more codes here
You have defined the myCalculator object as a local variable inside your main method which is why if you try to reference it outside you get cannot be resolved error.
Did you try defining the myCalculator object reference outside your main method like this:-
private static Calculator myCalculator = null;
public static void main(String [] args)
{
try{
CalculatorFactory theWorks = (CalculatorFactory)Naming.lookup("rmi://localhost:13456/CalculationsAnon");
myCalculator = theWorks.newCalculator();
// You rest of the code here