2014-09-20 146 views
0

我想在我的程序中使用不同的函數中的對象。用不同的方法初始化變量/對象與全局初始化

殼體1:

class a 
{ 
public Scanner s; //the object 
    method1() 
    { 
    s=new scanner(System.in); 
    s.close(); 
    } 

    method2() 
    { 
    s=new scanner(System.in); 
    s.close(); 
    } 
    p s main(String[] args) 
{ 
    method1(); 
    method2(); 
} 

} 

殼體2:

class a 
{ 
public Scanner s=Scanner(System.in); 
    method1() 
    { 
    //functions with s 
    } 

method2() 
    { 
     //functions with s 

    } 

    main() 
    { 
    method1(); 
    method2(); 
    } 

} 

如果我在CASE 1關閉對象在一個函數,我不能訪問它。 哪個CASE已優化?我應該使用哪一個?在開始時初始化它們會更好嗎?

+0

使用情況1,因爲每個*方法*(在Java中,他們是所謂的方法),你打算使用它們,而且我看到,你也必須關閉它們。所以在這種情況下使用第二種情況是行不通的。 – lxcky 2014-09-20 08:26:18

+1

請花時間寫出真實的代碼並正確縮進。你在尋求幫助。你不想讓人們猜測你在問什麼。 – 2014-09-20 08:26:27

回答

0

我會與解決方案去case1

case 1: 
     class a 
     { 
      public Scanner s; //the object 
      method1() 
      { 
       s=new scanner(System.in); 
       s.close(); 
      } 

      method2() 
      { 
       s=new scanner(System.in); 
       s.close(); 
      } 
      p s main(String[] args) 
      { 
       method1(); 
       method2(); 
      } 
     } 
    } 
+0

請問爲什麼你會用case1去任何特定的原因? – SilentKiller 2014-09-23 06:57:41