2014-03-05 275 views
-5

我不明白这个错误,它要求我把一个分号放在一个封闭的大括号中。从我的理解,花括号结束了一段代码,为什么我需要添加分号?Java编译错误';' '}'

我的代码:

import java.util.*; 

public class textdisplay { 
    public static void main(String[] args) { 

String text = "null"; 
String more = "y"; 
String string1, string2; 

Scanner keyboard = new Scanner (System.in); 


    while (more.charAt(0) == 'y' || more.charAt(0) == 'Y') { 

     System.out.println("\n\t\t\t Enter 2 strings of text :)"); 
     System.out.print("\n\t\tString 1: "); 
     string1 = keyboard.nextLine(); 
     System.out.print("\n\t\tString 2: "); 
     string2 = keyboard.nextLine(); 
     System.out.print("Your combined strings: " + methods.textAdder(string1, string2)); 

    System.out.print("\n\t\t\t Do more (Y/N)? "); 
    more = keyboard.next(); 

    } 

    class methods { 
     String textAdder(String string1, String string2); 
     return string1 + string2; 
    } 
} 
} 

Error: 
textdisplay.java:29: error: illegal start of type 
        return string1 + string2; 
        ^
textdisplay.java:29: error: ';' expected 
        return string1 + string2; 
         ^
textdisplay.java:29: error: illegal start of type 
        return string1 + string2; 
           ^
+0

你有一个'class methods',里面有一些随机代码。语句必须位于初始化程序,构造函数或方法中。 –

+0

哪一行? (提示:它是'String textAdder(String string1,String string2);'这应该做什么?) – iamnotmaynard

+0

'class methods'在'main'方法体内。你不能在这样的方法中定义一个命名类。 – Wyzard

回答

3

methods类中的textAdder方法是什么原因造成你的麻烦,因为没有定义方法体。简单地解决这个问题是这样的:

String textAdder(String string1, String string2) 
{ 
    return string1 + string2; 
} 

但你通过一个静态方法访问局部类此方法。这是不允许的。只需在该方法内创建类的实例,或将该方法移至主类,然后将static关键字添加到该类。

+0

如何?它可以防止他的错误,即使他的代码结构不好。 – Arbiter

+0

哦,你说得对。感谢您通知我。答案已更新。 – Arbiter

+0

哦,你又是对的,从来没有真正使用过当地的内部类,所以不会知道。再次感谢你。 – Arbiter