【问题标题】:"Syntax error on token *********, annotationName expected after this token"“令牌 ********* 上的语法错误,此令牌后应有 annotationName”
【发布时间】:2014-11-28 17:17:45
【问题描述】:

我有两个我无法解决的错误,谷歌没有让我清楚地知道问题是什么。 我得到两个编译错误,一个就行了

Random random = new Random();

在 ; 之后,说 { 预期的。下一个错误在这一行

public void newGame() {

说“令牌 newGame 上的语法错误,此令牌后应有 annotationName”。这是什么意思?我的代码底部有一个额外的 },如果我删除它,编译器(Eclipse)会抱怨。如果我删除它,它会在最后一个 } 上显示 }。

欢迎任何正确方向的指点,但请不要乱喂。 :) 我想学习。如果我在任何地方都违反了 Java 约定,请也指出这一点。谢谢!

完整代码:

import java.awt.*;
import java.io.*;
import javax.swing.*;
import java.util.Random;

public class Memory {

    File folder = (new File("mypictures"));
    File[] pictures = folder.listFiles();
    ImageIcon im = new ImageIcon();
    Card[] allCards;
    Random random = new Random();

    for(int i = 0; i < im.length; i++) {
        allCards[i] = new Card(new ImageIcon(pictures[i].getPath()));
    }

    public void newGame() {
        int row = Integer.parseInt
                (JOptionPane.showInputDialog("How many rows?"));
        int column = Integer.parseInt
                (JOptionPane.showInputDialog("How many columns?"));

        Card[] game = new Card[row*column];

        for(i = 0; i < game.length; i++) {
            int ranint = random.nextInt(game.length);
            game[i] = allCards[ranint];
            Card c = game[i].copy();
            game[i+game.length/2] = c;
        }

        for(i = 0; i < 5; i++) { // Randomizing a few times.
            Tools.randomOrder(game);
        }

        JFrame jf = new JFrame("Memory");
        jf.setLayout (new GridLayout (row, column));

        for(i = 0; i < game.length; i++) { // Adds the cards to our grid.
            jf.add(game[1]);
        }
    }
}
}

【问题讨论】:

  • 你认为应该在什么时候执行类体中间的for循环?你为什么这么认为?
  • 为什么循环for(int i = 0; i &lt; im.length; i++)不在方法中?

标签: java this token


【解决方案1】:

您的第一个循环需要放在类的方法中。如果您希望在创建此类对象时执行该循环,则必须编写如下构造方法:

public Memory() {
    for(int i = 0; i < im.length; i++) {
        allCards[i] = new Card(new ImageIcon(pictures[i].getPath()));
    }
}

但是,您不能以这种方式为数组赋值,因为allCards 只是一个包含null 的空变量。您必须像这样初始化变量:

Card [] allCards = new allCards[desiredLength];

【讨论】:

  • 很好的答案,既然你这样说,那么它为什么不起作用就很有意义了。谢谢!
【解决方案2】:

问题是第一个 for 循环。在 Java 中,您不能只将代码放在类下——它需要放在方法、构造函数或匿名块中。由于这看起来像是初始化代码,因此构造函数似乎很合适:

public class Memory {

    File folder = (new File("mypictures"));
    File[] pictures = folder.listFiles();
    ImageIcon im = new ImageIcon();
    Card[] allCards;
    Random random = new Random();

    /** Defaylt constructor to initialize allCards: */
    public Memory() {
        allCards = new Crad[im.length];
        for(int i = 0; i < im.length; i++) {
            allCards[i] = new Card(new ImageIcon(pictures[i].getPath()));
        }
    }

    // rest of the class

【讨论】:

  • 另外,allCards需要先初始化
  • @JeffShaw 不错 - 已修复。
猜你喜欢
  • 2015-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-27
  • 1970-01-01
  • 2014-02-16
  • 1970-01-01
相关资源
最近更新 更多