2014-08-31 159 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)在另一種方法中可用?

在該方法中執行查找,或將主要方法的查找結果存儲到靜態或實例變量而不是局部變量中。