2014-08-31 105 views
0

我是RMI的新手,尝试将以下内容应用到正在处理的项目中。
这段代码Naming.lookup...... theWork.newCalculator();总是需要在main方法中吗?
可以拨打myCalculator以外main方法吗?
当我尝试时,我得到myCalculator cannot be resolved错误。
以下示例在main中调用myCalculator,以便能够正常工作。如何使myCalculator.plus(arg)在另一种方法中可用?RMI客户端方法调用

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 
+0

请告诉我们你已经尝试过了。 – 2014-08-31 09:07:25

回答

1

您已经定义了myCalculator对象作为你的主要方法内部的局部变量这就是为什么如果你尝试引用它之外,你得到解决不了错误。

你尝试你的主要方法之外定义这样的myCalculator对象引用: -

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 
+0

@kbear我的荣幸 – 2014-08-31 09:32:27

0

请问这一段代码“...... Naming.lookup theWork.newCalculator(); “总是需要在主要方法?

我能叫myCalculator外主要方法是什么?

是的,只要您有权访问theWorks变量。

当我尝试时,我得到myCalculator cannot be resolved错误。

这是一个编译错误。提到的变量不在范围内。它完全与RMI无关,只是一个常见的编程错误。

下面的例子调用myCalculator在main中,所以它的工作原理。如何使myCalculator.plus(arg)在另一种方法中可用?

在该方法中执行查找,或将主要方法的查找结果存储到静态或实例变量而不是局部变量中。