2011-12-30 115 views
-4

Exception in thread "main" java.lang.Error: Unresolved compilation problem: Syntax error on token "]", invalid (线程“主”中的异常

这就是我得到的错误消息。 这是我的代码:

import java.awt.*; 
import java.util.Random; 
import java.awt.event.*; 
import javax.swing.*; //notice javax 
public class Frame1 extends JFrame 
{ 
    JPanel pane = new JPanel(); 
    Frame1() // the frame constructor method 
    { 
    super("Harry's Random Number Generator"); setBounds(100,100,300,100); 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    Container con = this.getContentPane(); // inherit main frame 
    con.add(pane); // add the panel to frame 
    // customize panel here 
    // pane.add(someWidget); 
    setVisible(true); // display this frame 
    } 
    public static void main(String args[]) {new Frame1();} 
    Random dice = new Random(); 
    int number;{ 

    for(int counter=1; counter<10;counter++){ 
     number = 1+dice.nextInt(1000); 
     System.out.println(number + " "); 
    } 

    } 

} 
+0

哪条线发生错误?你能发布完整的堆栈跟踪吗? – 2011-12-30 23:58:38

+0

您给我们的代码不包含您发布的错误。该程序如图所示运行,但除了打印一些数字并在屏幕上显示一个灰色框架外,其他程序并没有多大作用。 – Paul 2011-12-31 00:02:27

+0

然后你可能会使用Eclipse。按Alt-Shift-Q然后按X(或转到窗口 - 显示视图 - 问题)。您将在此视图中找到编译错误消息。阅读它们,并解决编译问题。 您的代码会更具可读性,如果它正确缩进,您会更容易注意到这些错误。在编辑器中按Ctrl-Shift-F以格式化代码。 – 2011-12-31 00:10:44

回答

2

你的代码是完全搞砸了。

这些行:

public static void main(String args[]) {new Frame1();} 
    Random dice = new Random(); 

开始和结束的主要方法,并且然后定义一个构件变量dice

这些行:

int number;{ 

for(int counter=1; counter<10;counter++){ 
    number = 1+dice.nextInt(1000); 
    System.out.println(number + " "); 
} 

} 

然后去和定义另一个成员变量number然后一个实例初始化{ ... }

通过正确地格式化您的代码开始。在语法上来讲,我会写这样的:

import java.awt.Container; 

public class Frame1 extends JFrame { 

    JPanel pane = new JPanel(); 

    Frame1() { // the frame constructor method 
     super("Harry's Random Number Generator"); 
     setBounds(100,100,300,100); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     Container con = this.getContentPane(); // inherit main frame 
     con.add(pane); // add the panel to frame 
     // customize panel here 
     // pane.add(someWidget); 
     setVisible(true); // display this frame 
    } 

    public static void main(String args[]) { 
     new Frame1(); 

     Random dice = new Random(); 
     int number; 

     for(int counter=1; counter<10;counter++){ 
      number = 1+dice.nextInt(1000); 
      System.out.println(number + " "); 
     } 
    } 
} 

(事实上,编译和运行“精”。)

+0

但是,这并不回答他的问题。 – Paul 2011-12-31 00:03:23

+1

是的。答案已更新。 – aioobe 2011-12-31 00:05:06

0

你的主要方法是一条线,新的帧1();那么你关闭main()并且出现一些新的代码:Random dice = ...但是没有封装在方法中。

+0

这是真的,但它没有解释导致异常的异常或编译。 – 2011-12-31 01:21:51

相关问题