i am having two errors i can not solve, google didn't give me a clear idea of what the problem was. I get two compiling errors, one on the line
Random random = new Random();
right after the ;, saying { expected. The next error is at this line
public void newGame() {
saying "Syntax error on token newGame, annotationName expected after this token". What does this mean? I have an extra } at the bottom of my code, the compiler (Eclipse) complains if i remove this. It says } expected on the last } if i remove it.
Any pointers in the right direction is welcome, but no spoonfeeding please. :) I want to learn. If i am breaking java convention anywhere, please point that out aswell. Thanks!
whole code:
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]);
}
}
}
}
Your first loop needs to be put inside a method of the class. In case you want that loop to be executed upon the creation of an object of such class, you must write a constructor method like this:
public Memory() {
for(int i = 0; i < im.length; i++) {
allCards[i] = new Card(new ImageIcon(pictures[i].getPath()));
}
}
However, you can't assign values to an array this way, because allCards
is just an empty variable holding null
. You must initialize the variable like this:
Card [] allCards = new allCards[desiredLength];