2014-01-25 58 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

应用这种做法将确保你不会在你的项目中的任何地方静态/非静态的问题,因为只有静态的是初始化你的实际代码,然后处理所有代码/进一步启动其他类(这是所有非静态的)

相关问题