2017-04-22 79 views
-3
public class Gfg { 

    // constructor 
    Gfg() 
    { 
     System.out.println("Geeksforgeeks"); 
    } 

    System.out.println("hi"); 


    public static void main(String args[]) 
    { 
     Gfg b; 
     b = new Gfg(); 
    } 

} 

當我正在寫sopln()main()或在類中的方法,那麼它沒有給出任何錯誤,但是當我在上面寫的類時,它是給出錯誤。爲什麼這樣?爲什麼sopln()給出錯誤?

+3

歡迎使用堆棧溢出!請[參觀](http://stackoverflow.com/tour)以查看網站的工作原理和問題,並相應地編輯您的問題。另請參閱:[如何創建最小,完整和可驗證的示例](http://stackoverflow.com/help/mcve) –

+3

'System.out.println(「hi」);'應該放在'{} –

+0

爲什麼?因爲根據Java語法不允許。順便說一句。目前還不清楚這意味着什麼。 – Henry

回答

2

因爲在Java的任何表達式語句應該是{}之間,所以你可以使用它像main方法的方法中,或者例如靜態塊中:

{ 
    System.out.println("hi"); 
} 

看看herehere

1

您需要在方法中結束語句,如

public class Gfg { 

    Gfg(){ 
     System.out.println("Geeksforgeeks"); 
     dummyMethod(); 
    } 

    public void dummyMethod(){ 
     System.out.println("hi"); 
    } 
..///rest of code