【问题标题】:Exception in thread "main" [closed]线程“main”中的异常[关闭]
【发布时间】:2011-12-30 23:56:45
【问题描述】:

线程“main”java.lang.Error 中的异常:未解决的编译问题: 标记“]”的语法错误,无效(

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

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 + " ");
    }

    }

}

【问题讨论】:

  • 错误出现在哪一行?你能发布一个完整的堆栈跟踪吗?
  • 您提供给我们的代码不包含您发布的错误。程序如图所示运行,但除了打印一些数字并在屏幕上抛出一个灰色框外,它并没有做太多事情。
  • 那时您可能正在使用 Eclipse。按 Alt-Shift-Q,然后按 X(或转到窗口 - 显示视图 - 问题)。您将在此视图中找到编译错误消息。阅读它们,并修复编译问题。如果缩进正确,您的代码将更具可读性,并且您会更容易注意到错误。在编辑器中按 Ctrl-Shift-F 格式化代码。

标签: java


【解决方案1】:

你的代码完全搞砸了。

这些行:

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

开始和结束main方法,然后定义一个成员变量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 + " ");
        }
    }
}

(实际上编译和运行“很好”。)

【讨论】:

  • 然而,这并不能回答他的问题。
【解决方案2】:

您的主要方法是一行:new Frame1();然后关闭 main() 并出现一些新代码:Random dice = ... 但未封装在方法中。

【讨论】:

  • 这是对的,但它并没有解释异常或导致异常的编译。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-05
  • 2014-11-14
  • 1970-01-01
  • 1970-01-01
  • 2011-10-26
相关资源
最近更新 更多