2012-10-09 89 views
2

只是一个简单的类将调用打印数组的类。 Eclipse中出现语法错误。我也遇到一个错误,我没有一个叫做Kremalation的方法。令牌上的语法错误“;”,“{”在此令牌后预期

public class AytiMain { 

    public static void main(String[] args) { 
     AytiMain.Kremalation(); 
    } 
} 

public class Kremalation { 

    String[] ena = { "PEINAW", "PEINOUSA", "PETHAINW" }; 
    int i; // <= syntax error on token ";", { expected after this token 

    for (i = 0; i <= ena.lenght; i++) 
     System.out.println(ena[i]); 
} 
} 
+1

好了,你没有** **方法'Kremalation ',你有** class ** Kremalation'(它的代码在任何方法之外)。 – Baz

回答

5

您有代码(未声明变量和/或对其进行初始化)ouside一个方法,该方法是:

for (i=0; i<=ena.lenght; i++) 
    System.out.println(ena[i]); 

在Java中,代码MUST驻留内一个方法。你不能调用一个类,你必须调用里面的一个方法一个类。

WRONG

class ClassName { 
    for (...) 
} 

正确

class ClassName { 
    static void method() { 
    for (...) 
    } 

    public static void main(String[] args) { 
    ClassName.method(); 
    } 
} 
2

您不能将方法定义为类。 它应该是

public static void kremalation() 
{ 
String ena[]={"PEINAW","PEINOUSA","PETHAINW"}; 
int i; 
for (i=0; i<=ena.lenght; i++) 
    System.out.println(ena[i]); 
} 
0

两个可能的答案。

1)如果您想将其定义为类,请将其从第二个移除。

2)在关闭大括号内移动Kremalation并将其替换为void,并使其成为静态方法。

+0

这是行不通的,因为该方法需要返回类型。 –

+0

@MattLeidholm:哪种方法?抱歉!我明白你的意思了。 – kosa

+0

将Kremalation“class”变为静态方法后,仍然需要返回类型(或“void”)。我看到你只是编辑了你的答案来包含它。没关系。 –

1
public class AytiMain { 


    public static void main(String[] args) { 
     AytiMain.Kremalation(); 
    } 

    public static void Kremalation() {// change here. 

     String ena[]={"PEINAW","PEINOUSA","PETHAINW"}; 
     int i; 

     for (i=0; i<=ena.lenght; i++) 
      System.out.println(ena[i]); 

    }  
} 
0

你不能有可执行代码直接在类中..添加的方法和使用类的实例调用该方法..

public class Kremalation { 

    public void method() { 

     String ena[]={"PEINAW","PEINOUSA","PETHAINW"}; 
     int i; 

     for (i=0; i<=ena.lenght; i++) 
      System.out.println(ena[i]); 
    } 

} 

现在,在你的主要方法,写: -

public static void main(String[] args) { 
    new Kremalation().method();  
} 
0

两种方法来解决这个问题.....

1日有2班在同一个文件:

public class AytiMain { 


    public static void main(String[] args) { 

     new Kremalation().doIt(); 
    } 

} 

class Kremalation { 

    public void doIt(){  // In Java Codes should be in blocks 
          // Like methods or instance initializer blocks 

    String ena[]={"PEINAW","PEINOUSA","PETHAINW"}; 
    int i; 

    for (i=0; i<=ena.lenght; i++) 
     System.out.println(ena[i]); 

    } 

} 

第二变化的类方法:

public class AytiMain { 


    public static void main(String[] args) { 
     AytiMain.Kremalation(); 
    } 

    public static void Kremalation() {  // change here. 

     String ena[]={"PEINAW","PEINOUSA","PETHAINW"}; 
     int i; 

     for (i=0; i<=ena.lenght; i++) 
      System.out.println(ena[i]); 

    }  
} 
相关问题