2014-01-25 60 views
-1

下面給出的代碼給出了以下錯誤: - 非靜態方法compute(int)不能從靜態上下文中引用 如果我無法創建main()裏面的方法,我該怎麼做。非靜態方法compute(int)不能從靜態上下文中引用

class Ideone 
{ 
public static void main (String[] args) throws java.lang.Exception 
{ 
    Scanner key = new Scanner(System.in); 
    int t = key.nextInt(); 
    for(int i=0;i<t;i++){ 
     int a = key.nextInt(); 
     int b = key.nextInt(); 
     a=compute(a); 
     b=compute(b); 
     System.out.println(a+b); 
    } 
} 
int compute(int a){ 
    int basea=0, digit; 
    int temp=a; 
    while(temp>0){ 
     digit = temp%10; 
     temp/=10; 
     if(digit>(basea-1))basea=digit+1; 
    } 
    temp=a; 
    a=0; 
    int count=0; 
    while(temp>0){ 
     digit = temp%10; 
     temp/=10; 
     a+=digit*Math.pow(basea,count); 
     count++; 
    } 
    return a; 
} 
+1

'static vs non-static'你不能在靜態中使用非靜態方法方法。 –

回答

0

你有兩個選擇:

  1. 聲明compute()靜:

    static int compute(int a){ 
    
  2. 創建的IdeOne一個實例,並通過該引用調用compute()

    IdeOne ideOne = new IdeOne(); 
    a = ideOne.compute(a); 
    

我認爲這是一個好主意,通過Java tutorials on classes and objects閱讀。

0

你試圖從靜態方法(主)調用一個非靜態方法(這是計算)。

變化int compute(int a){static int compute(int a){

0

在你的情況進行方法compute靜態的。否則,創建一個Ideone對象並在其上調用您的方法。

0

您不能從static方法訪問non-static方法。
您嘗試訪問的方法是實例級方法,您無法訪問實例方法/變量而無需類實例。
您無法訪問不存在的內容。默認情況下,非靜態方法尚不存在,直到您創建該方法所在類的對象。靜態方法總是存在。

您可以通過以下方式訪問您的方法:
1.請您compute()方法靜態

int compute(int a){ 
    ///rest of your code 
} 

2.類對象創建類Ideone和訪問方法的實例。

IdeOne obj = new IdeOne(); 
obj.compute(a); 
obj.compute(b); 
0

這裏給出的答案主要是爲了使方法static,這對於這個規模的程序很好。然而,隨着項目變得越來越大,並不是所有的東西都會在你的主體中,因此你會在更大的範圍內得到這個靜態/非靜態問題,因爲其他類不會是靜態的。

解決方案就成爲使一個類爲您Main,因爲這樣的:

public class Main { 

public static void main(String[] args) { 

Ideone ideone = new Ideone(); 

然後另一個裏面有文件的class Ideone

public class Ideone { 

Scanner key; 

public Ideone() { 

    key = new Scanner(System.in); 
    int t = key.nextInt(); 
    for(int i=0;i<t;i++){ 
     int a = key.nextInt(); 
     int b = key.nextInt(); 
     a=compute(a); 
     b=compute(b); 
     System.out.println(a+b); 

    } // end constructor 

    int compute(int a){ 
     int basea=0, digit; 
     int temp=a; 
     while(temp>0){ 
     digit = temp%10; 
     temp/=10; 
     if(digit>(basea-1))basea=digit+1; 
    } 
    temp=a; 
    a=0; 
    int count=0; 
    while(temp>0){ 
     digit = temp%10; 
     temp/=10; 
     a+=digit*Math.pow(basea,count); 
     count++; 
    } 
    return a; 
    } // end compute 

} // end class 

至於你的主文件。我做的工作,但更好的做法是遵循這裏給出的代碼示例:

http://docs.oracle.com/javase/tutorial/uiswing/painting/step1.html

應用這種做法將確保你不會在你的項目中的任何地方靜態/非靜態的問題,因爲只有靜態的是初始化你的實際代碼,然後處理所有代碼/進一步啓動其他類(這是所有非靜態的)

相關問題