“令牌 ********* 出现语法错误,此令牌后应有注释名称”

问题描述 投票:0回答:3

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

Random random = new Random();

紧接在;之后,表示{预期。下一个错误就在这一行

public void newGame() {

说“令牌 newGame 上有语法错误,此令牌后应有注释名称”。这是什么意思?我的代码底部有一个额外的 },如果我删除它,编译器(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]);
        }
    }
}
}
java this token
3个回答
2
投票

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

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];

0
投票

问题出在第一个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

0
投票

右键单击项目 -> 配置构建路径 -> 库 -> 添加选择执行环境为 JavaSE-11(jre)

© www.soinside.com 2019 - 2024. All rights reserved.