Getting error "package X does not exist" in Java - java
import java.util.*; ...
ArrayList<String> stringList = new ArrayList<String>();
stringList.add("Item");
This is my Java code. The final line gets the error: "package stringList does not exist".
How can I get rid of this error and start adding items to my list? I can only imagine I'm missing something very simple. Thanks in advance.
Partially per request, below is my whole code. It's incomplete, but I'm stuck on the above problem.
package gorobot_m5d25y2013;
//import java.util.List;
import java.util.ArrayList;
class Engine { // The Engine will show the best positions on the board given a particular board setup.
// Some project-wide constants and variables.
final int BLACK = 1; // Black go pieces... black goes first in the game of go, unless black has
// a 2 stone or greater handicap.
final int WHITE = 2; // White go pieces... usually goes second in the game.
final int EMPTY = 0; // An empty space, no piece is on it.
final int VIRTUAL = -1; // This is a space outside of the board that can never be played on,
// but is useful if there's ever an issue of checking something for
// the board which would normally be out of bounds.
final int BLACKS_TURN = 1;
final int WHITES_TURN = 2;
final int BOARD_SIZE = 19; // Access with Global.BOARD_SIZE ... this is the width of the board.
final int VIRTUAL_BOARD_BORDER = 10; // This is the width of the empty space around each of the four sides of the board.
int whoseTurn; // 1 is blacks turn, 2 is white's turn.
int totalGames = 0;
int blackWins = 0;
static long groupCounter = 1; // Used in inner class group.
int positionNumber = 1; // Used in inner class group and position.
int[][] boardValues = new int[BOARD_SIZE][BOARD_SIZE]; // boardValues is the win probability for each position on the board.
Engine() {
Board firstMove = new Board();
}
int oppositeWhoseTurn() {
int opposite = 0;
if (whoseTurn == BLACKS_TURN) {
opposite = WHITES_TURN;
}
if (whoseTurn == WHITES_TURN) {
opposite = BLACKS_TURN;
}
if (opposite == 0) {
System.out.println("An error with the opposite variable has occured.");
}
return opposite;
}
int regPos(int boardPosition) { // This Regulates Position-Ex. takes any of the normal board positions, for example,
// 1-19, and sets it to the virtual, larger board. So a Position 1 move will be position 9 with a 10 space buffer.
int realBoardPosition = (boardPosition + (VIRTUAL_BOARD_BORDER - 1));
return realBoardPosition;
}
class Board { // The board is composed of positions and groups. At first it is 2 groups, the real and the virtual
int virtualPlusRegularBoardSize = (BOARD_SIZE + (VIRTUAL_BOARD_BORDER * 2));
Position[][] point = new Position[virtualPlusRegularBoardSize][virtualPlusRegularBoardSize];
Group food = new Group();
Board() {
for (int horizontal = 0; horizontal < virtualPlusRegularBoardSize; horizontal++) {
for (int vertical = 0; vertical < virtualPlusRegularBoardSize; vertical++) {
point[horizontal][vertical] = new Position(horizontal, vertical);
}
}
for (int horizontal = 1; horizontal <= BOARD_SIZE; horizontal++) {
for (int vertical = 1; vertical <= BOARD_SIZE; vertical++) {
point[regPos(horizontal)][regPos(vertical)].setType(EMPTY);
}
}
}
}
class Group { // Each Group is composed of positions
long groupNumber;
int sizeOfGroup = 1;
Integer[] ints = new Integer[1];
ArrayList<String> stringList = new ArrayList<String>();
stringList.add ("Item");
//List<Position> positionList = new ArrayList<>();
//positionList.size ();
//positionList.add ();
//positionList.remove("F");
Group() {
groupNumber = groupCounter;
groupCounter++;
}
void setGroupNumber(int newGroupNumber) {
sizeOfGroup = newGroupNumber;
}
long getGroupNumber() {
return groupNumber;
}
void setSizeOfGroup(int newGroupSize) {
sizeOfGroup = newGroupSize;
}
int getSizeOfGroup() {
return sizeOfGroup;
}
void addPositionToGroup(Position point) {
}
}
class Position { // Each position is either Empty, Black, White, or Virtual.
int pieceType; // VIRTUAL means it's not even a board position, at first all spaces are like this...
// but eventually, the positions on the actual board will all be empty - 0, and then
// will start filling with black - 1 and white - 2 pieces.
boolean legalMove; // This tells us whether this space is a legal move.
int numberOfLiberties = 2;
int virtualHorizontal;
int virtualVertical;
Position() {
pieceType = VIRTUAL;
legalMove = false;
}
Position(int horizontal, int vertical) {
pieceType = VIRTUAL;
legalMove = true;
virtualHorizontal = horizontal;
virtualVertical = vertical;
}
void setType(int setType) {
pieceType = setType;
////// Add in here the 4 surrounding sides and make those these variables accessible from the piece class.
if (setType == BLACK) {
}
if (setType == WHITE) {
}
}
int getType() {
return pieceType;
}
}
}
/**
*
* #author Eric Martin
*/
public class GoRobot_m5d25y2013 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Engine firstEngine = new Engine();
}
}
And these are my errors:
run:
Exception in thread "main" java.lang.ClassFormatError: Method "<error>" in class gorobot_m5d25y2013/Engine$Group has illegal signature "(Ljava/lang/Object;)LstringList/add;"
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:791)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
at gorobot_m5d25y2013.Engine$Board.<init>(GoRobot_m5d25y2013.java:73)
at gorobot_m5d25y2013.Engine.<init>(GoRobot_m5d25y2013.java:46)
at gorobot_m5d25y2013.GoRobot_m5d25y2013.main(GoRobot_m5d25y2013.java:181)
Java Result: 1
BUILD SUCCESSFUL (total time: 2 seconds)
From your edit, the problem is that you're calling stringList.add("Item"); in the class definition. The execution of methods from your class fields should be done inside a method. In your case, looks like this line should be inside your class constructor:
class Group { // Each Group is composed of positions
//fields definitions (and probably initialization of fields)...
//field declaration
ArrayList<String> stringList = new ArrayList<String>();
//this code can't be here
//stringList.add("Item");
Group() {
//move it here
stringList.add("Item");
//...
}
//rest of code...
}
This code is not generating any error and I think you have not put it in the class.You can try this.
import java.util.*;
public class One {
public static void main(String args[]) {
ArrayList<String> stringList=new ArrayList<String>();
stringList.add("Europe");
System.out.println(stringList);
}
}
You should create an object of Group.
Then use that object to access the list.
In main method try
Group g = new Group();
g.stringList.add("item");
Related
How to create a simple user interface to declare variables?
I am working on my first java project, one that simulates the behaviour of a neutrophil catching a bacterium (So random/semirandom particle behaviour). At the beginning of this program I have several variables (such as the radii of the organisms, etc) and right now they are fixed to the value I hardcoded in there. I want to create a user interface so that before the program starts, a screen pops up in which you can type in the values you want to use, and it uses those to run to program. Now I have used a swing script to create such a window and that looks a bit like this: Now I'm wondering how I could implement it such that I can take the values used in those text boxes and assign them to my variables in my program. This is the program I am referring to: package nanocourse; import java.awt.Color; import nano.*; import java.util.Random; import prescreen.PreScreen; public class Exercise3_final { public Exercise3_final() { int xSize = 1000; int ySize = 800; Canvas myScreen = new Canvas(xSize, ySize); Pen myPen = new Pen(myScreen); Random random = new Random(); int frame=0; //how many frames have passed since start program //properties bacterium int xPosBacterium=random.nextInt(xSize); //random starting position of bacterium int yPosBacterium=random.nextInt(ySize); int K=1000; //how many points used to draw bacterium double [] xValueBacterium = new double[K]; // double [] yValueBacterium = new double[K]; double bacteriumRadiusInput=20; double bacteriumRadius=bacteriumRadiusInput; //radius of bacterium boolean bacteriumAlive=true; //properties biomolecules int amountBio=30000; boolean [] bioExist = new boolean[amountBio]; int [] xPosBio = new int [amountBio]; int [] yPosBio = new int [amountBio]; int [] dXBio = new int [amountBio]; int [] dYBio = new int [amountBio]; int [] lifetimeBio = new int [amountBio]; double chanceDegrade=0.1; //chance that a biomolecule gets degraded per frame double chanceSynthesize=100; //chance that a biomolecule gets synthesized per frame for(int i=0;i<amountBio;i++) { bioExist[i]=false; //setting existing state to false } //properties Neutrophil int xPosNeutrophil=random.nextInt(xSize); int yPosNeutrophil=random.nextInt(ySize); int L=1000; double [] xValueNeutrophil= new double[L]; double [] yValueNeutrophil= new double[L]; double neutrophilRadius=40; double xVector, yVector, xNormVector,yNormVector,magnitude,xSumVector,ySumVector; double aggressiveness=1; while(bacteriumAlive==true) //while program is running { frame++; //1. Simulating a moving Bacterium int dXBacterium=random.nextInt(11)-5; //random motion int dYBacterium=random.nextInt(11)-5; xPosBacterium=xPosBacterium+dXBacterium; yPosBacterium=yPosBacterium+dYBacterium; if(xPosBacterium<(bacteriumRadius/2+2*myPen.getSize())) //boundaries bacterium,accounting for size bacterium { xPosBacterium=(int)bacteriumRadius/2+2*myPen.getSize(); } else if(xPosBacterium>xSize - (bacteriumRadius/2+2*myPen.getSize())) { xPosBacterium=xSize - ((int)bacteriumRadius/2+2*myPen.getSize()); } else if(yPosBacterium<(bacteriumRadius/2+2*myPen.getSize())) { yPosBacterium=((int)bacteriumRadius/2+2*myPen.getSize()); } else if(yPosBacterium>ySize - (bacteriumRadius/2+2*myPen.getSize())) { yPosBacterium=ySize - ((int)bacteriumRadius/2+2*myPen.getSize()); } //2. Simulating synthesis and secretion of biomolecules by the bacterium. for(int i=0;i<amountBio;i++) { double synthesizeNumber=Math.random()*100; if(synthesizeNumber<chanceSynthesize && i==frame) { bioExist[frame]=true; //make the biomolecules exist } if(bioExist[i]==true && frame!=1) //if biomolecule exist apply motion { dXBio[i]=random.nextInt(41)-20; dYBio[i]=random.nextInt(41)-20; xPosBio[i]=xPosBio[i]+dXBio[i]; yPosBio[i]=yPosBio[i]+dYBio[i]; } else //if biomolecule doesn't exist, make position equal bacterium position { xPosBio[i]=xPosBacterium; yPosBio[i]=yPosBacterium; } if(xPosBio[i]>xSize) //boundaries biomolecules { xPosBio[i]=xSize; } if(xPosBio[i]<0) { xPosBio[i]=0; } if(yPosBio[i]>ySize) { yPosBio[i]=ySize; } if(yPosBio[i]<0) { yPosBio[i]=0; } if(bioExist[i]==true) { lifetimeBio[i]++; double degradationNumber=Math.random()*100; if(degradationNumber<chanceDegrade) { bioExist[i]=false; } } if(bioExist[i]==true && lifetimeBio[i]<=100) //if biomolecule lives shorter than 100 frames==>green { myPen.setColor(Color.GREEN); //drawing biomolecules myPen.setShape(Shape.CIRCLE); myPen.setSize(5); } if(bioExist[i]==true && (lifetimeBio[i]>100 && lifetimeBio[i]<=500)) //if biomolecule lives 101-500 frames==>green { myPen.setColor(Color.yellow); //drawing biomolecules myPen.setShape(Shape.CIRCLE); myPen.setSize(5); } if(bioExist[i]==true && (lifetimeBio[i]>500 && lifetimeBio[i]<=1000)) //if biomolecule lives 501-1000 frames==>orange { myPen.setColor(Color.ORANGE); //drawing biomolecules myPen.setShape(Shape.CIRCLE); myPen.setSize(5); } if(bioExist[i]==true && (lifetimeBio[i]>1000 && lifetimeBio[i]<=1500)) //if biomolecule lives 1001-1500 frames==>red { myPen.setColor(Color.RED); //drawing biomolecules myPen.setShape(Shape.CIRCLE); myPen.setSize(5); } if(bioExist[i]==true && lifetimeBio[i]>1500) //if biomolecule lives 2001+ frames==>magenta { myPen.setColor(Color.magenta); //drawing biomolecules myPen.setShape(Shape.CIRCLE); myPen.setSize(5); } if(bioExist[i]==true) { myPen.draw(xPosBio[i],yPosBio[i]); } if(Math.sqrt(Math.pow(Math.abs(xPosBio[i]-xPosNeutrophil),2)+Math.pow(Math.abs(yPosBio[i]-yPosNeutrophil), 2))<neutrophilRadius) { bioExist[i]=false; //degrade if inside neutrophil } } if(bacteriumAlive==true) { for(int i = 0; i <K ; i++) //defining circle, drawing points, placed here because it needs to be on top { xValueBacterium[i] = bacteriumRadius*Math.cos(2*Math.PI*i/K); yValueBacterium[i] = bacteriumRadius*Math.sin(2*Math.PI*i/K); myPen.setColor(Color.red); myPen.setShape(Shape.CIRCLE); myPen.setSize(5); myPen.draw((int)xValueBacterium[i]+xPosBacterium,(int)yValueBacterium[i]+yPosBacterium); } } //5. Simulating the neutrophil eating the bacteriun xSumVector=0; ySumVector=0; for(int i=0;i<amountBio;i++) { if(Math.abs(xPosBio[i]-xPosNeutrophil)<(30+neutrophilRadius) && Math.abs(yPosBio[i]-yPosNeutrophil)<(30+neutrophilRadius) && bioExist[i]==true) { xVector=xPosBio[i]-xPosNeutrophil; yVector=yPosBio[i]-yPosNeutrophil; magnitude=Math.sqrt(Math.pow(xVector, 2)+Math.pow(yVector, 2)); xNormVector=xVector/magnitude; yNormVector=yVector/magnitude; xSumVector=xSumVector+xNormVector; ySumVector=ySumVector+yNormVector; } } //3. Simulating a moving neutrophil int dXNeutrophil=random.nextInt(11)-5+(int)aggressiveness*(int)xSumVector; //random motion int dYNeutrophil=random.nextInt(11)-5+(int)aggressiveness*(int)ySumVector; xPosNeutrophil=xPosNeutrophil+dXNeutrophil; yPosNeutrophil=yPosNeutrophil+dYNeutrophil; myPen.setSize(8); if(xPosNeutrophil<(neutrophilRadius/2+2*myPen.getSize())) //boundaries neutrophil { xPosNeutrophil=(int)neutrophilRadius/2+2*myPen.getSize(); } else if(xPosNeutrophil>xSize - (neutrophilRadius/2+2*myPen.getSize())) { xPosNeutrophil=xSize - ((int)neutrophilRadius/2+2*myPen.getSize()); } else if(yPosNeutrophil<(neutrophilRadius/2+2*myPen.getSize())) { yPosNeutrophil=((int)neutrophilRadius/2+2*myPen.getSize()); } else if(yPosNeutrophil>ySize - (neutrophilRadius/2+2*myPen.getSize())) { yPosNeutrophil=ySize - ((int)neutrophilRadius/2+2*myPen.getSize()); } for(int i = 0; i <L ; i++) //defining circle, drawing points, placed here because it needs to be on top { xValueNeutrophil[i] = neutrophilRadius*Math.cos(2*Math.PI*i/L); yValueNeutrophil[i] = neutrophilRadius*Math.sin(2*Math.PI*i/L); myPen.setColor(Color.blue); myPen.setShape(Shape.CIRCLE); myPen.draw((int)xValueNeutrophil[i]+xPosNeutrophil,(int)yValueNeutrophil[i]+yPosNeutrophil); } if(Math.abs(xPosNeutrophil-xPosBacterium)<2*bacteriumRadiusInput && Math.abs(yPosNeutrophil-yPosBacterium)<2*bacteriumRadiusInput && bacteriumRadius >=0) { bacteriumRadius=bacteriumRadius-1; if(bacteriumRadius==0) { bacteriumAlive=false; } } if(bacteriumAlive==false) { bacteriumAlive=true; xPosBacterium=random.nextInt(xSize); //random starting position of bacterium yPosBacterium=random.nextInt(ySize); bacteriumRadius=bacteriumRadiusInput; } myScreen.update(); //updating/refreshing screen myScreen.pause(10); myScreen.clear(); } } public static void main(String[] args) { Exercise3_final e = new Exercise3_final(); } } Any help would be appreciated!
Sounds like you need an action listener on the "Run!" button from your dialog: _run.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // set the variables here by getting the text from the inputs field1Var = Integer.parseInt(field1Input.getText()); field2Var = Integer.parseInt(field2Input.getText()); ... } });
I would suggest creating a singleton class to save all the values that are captured from the first screen (options menu screen). You can get the instance of this class anywhere in the application later on and use it. Advantages would be: - You will not have to carry forward the values everywhere in the application. - The values captured will the persisted till the application is shut down. Note: Make sure to add validations while fetching values from the options menu so that incorrect values are not set.
How to generate Random number based on range within List size without accessing zero
I have an Ant Colony Simulator. It is a 27 x 27 grid, and there is a Forager Ant class which locates food and the highest pheromone levels. I need to randomly generate the movement within a range. This is a very large project, so here is only the method in question (if that's enough): private GridNode locateHighestPherms() { Random randomNode = new Random(); LinkedList<GridNode> neighborNodeList = gridLocation.getNeighboringNodes(); //a List of Node Objects that keeps track of adjacent nodes LinkedList<GridNode> randomGridNode = new LinkedList<>(); //random destination Node for(Iterator<GridNode> gridNodeIterator = neighborNodeList.iterator(); gridNodeIterator.hasNext();) { GridNode alreadyVisited = gridNodeIterator.next(); if(foragerMoveHistory.contains(alreadyVisited) || !alreadyVisited.isVisible()) { gridNodeIterator.remove(); } } if(neighborNodeList.size() == 0) { neighborNodeList = gridLocation.getNeighboringNodes(); } GridNode nodeWithMostPherms = neighborNodeList.get(0); for(int checkNode = 1; checkNode < neighborNodeList.size(); checkNode++) { if(nodeWithMostPherms.isVisible() && nodeWithMostPherms.getPheromoneUnit() < neighborNodeList.get(checkNode).getPheromoneUnit()) { nodeWithMostPherms = neighborNodeList.get(checkNode); } } for (GridNode neighborNode : neighborNodeList) { if ((neighborNode.getPheromoneUnit() == nodeWithMostPherms.getPheromoneUnit()) && neighborNode.isVisible()) { randomGridNode.add(neighborNode); } } //DEBUGGING //System.out.println(randomGridNode.size()); nodeWithMostPherms = randomGridNode.get(randomNode.nextInt(randomGridNode.size())); //nodeWithMostPherms = randomGridNode.get(RandomInstance.randomNumberGen(1, randomGridNode.size())); return nodeWithMostPherms; } } Right there ^ the assignment to nodeWithMostPherms is where I need to access the next Random number. However, when I originally tried the code that's commented out, it was crashing because at times I was trying to access zero when the list size was zero. I will show you my RandomInstance class. It's short and sweet: import java.util.Random; public class RandomInstance { static int randomNumber; public static int randomNumberGen(int lowRange, int highRange) { Random numberGenerator = new Random(); //I would prefer not to have this. randomNumber = numberGenerator.nextInt(highRange - lowRange + 1) + lowRange; /** EXAMPLE FOR REFERENCE * setFoodUnitAmount(RandomInstance.randomNumberGen(500, 1000)); */ return randomNumber; } } The reason I have my own Random class is because there are many instances of random numbers that are generated, and it was suggested to create our own so we don't have a bunch of instances of java.util.Random all over the place. Does anyone have any suggestions on how I can make this fit my RandomInstance class? If I try the code that's commented out, it throws an IndexOutOfBoundsException Exception in thread "Thread-0" java.lang.IndexOutOfBoundsException: Index: 8, Size: 8 at java.util.LinkedList.checkElementIndex(LinkedList.java:555) at java.util.LinkedList.get(LinkedList.java:476) at ForagerObject.locateHighestPherms(ForagerObject.java:121) Line 121 is the assignment in question mentioned above.
While you can have Random shared, you shouldn't share a multiple field. public class RandomInstance { private final Random random = new Random(); public int nextInt(int min, int max) { return random.nextInt(max - min + 1) + min; } } so when you call it nodeWithMostPherms = randomGridNode.get(randomInstance.nextInt(1, randomGridNode.size()-1)); or you could use Random directly nodeWithMostPherms = randomGridNode.get(random.nextInt(randomGridNode.size()-1)+1);
incompatible types found : void, what is wrong?
I am trying to write a class that find the closest two vectors and return a sum. I have tried to understand so hard but I can't find the reason why I get this message, it's the only error I get: java:93: incompatible types found : void required: EDU.gatech.cc.is.util.Vec2 result = one.add(two); ^ Line 93 is at the end of the code, I put some arrows to indicate it! enter code here package EDU.gatech.cc.is.clay; import java.util.*; import EDU.gatech.cc.is.clay.*; import java.lang.*; import EDU.gatech.cc.is.abstractrobot.*; import EDU.gatech.cc.is.util.Vec2; import EDU.gatech.cc.is.util.Units; public class MAX_go_in_between extends NodeVec2 { public static final boolean DEBUG = /*true;*/ Node.DEBUG; private SocSmall abstract_robot; public MAX_go_in_between(SocSmall ar) { abstract_robot = ar; } long last_spott = 0; Vec2 result = new Vec2(); public Vec2 Value(long timestamp) { if (DEBUG) System.out.println("MAX_Avoid_walls: Value()"); if ((timestamp > last_spott) || (timestamp == -1)) { if (timestamp != -1) last_spott = timestamp; Vec2 one; Vec2 two; //array of Vec2 of all the opponents Vec2[] list_opp = abstract_robot.getOpponents(timestamp); //empty array of vec2 where will be put the opponents in front of the robot ArrayList<Vec2> list_opp_in_front; Vec2 temp; // find which opponents are in front and put them in the arraylist for(int i=0; i<list_opp.length; i++) { temp = list_opp[i]; if(temp.x >= 0.0) { list_opp_in_front.add(temp); } } //get closest opponent and sets it to index 0 for(int i=1; i<list_opp_in_front.size()-1; i++) { temp = list_opp_in_front.get(i); if(list_opp_in_front.get(0).r<temp.r) { list_opp_in_front.set(i, list_opp_in_front.get(0)); list_opp_in_front.set(0, temp); } } //get second closest opponent and sets it to index 1 for(int i=2; i<list_opp_in_front.size()-1; i++) { temp = list_opp_in_front.get(i); if(list_opp_in_front.get(1).r<temp.r) { list_opp_in_front.set(i, list_opp_in_front.get(1)); list_opp_in_front.set(1, temp); } // sum both vectors one = list_opp_in_front.get(0); two = list_opp_in_front.get(1); =============>>>> =============>>>> result = one.add(two); } } return(result); } } Here is the Vec2.add(Vec2) method: public void add(Vec2 other) { x = x + other.x; y = y + other.y; r = Math.sqrt(x*x + y*y); if (r > 0) t = Math.atan2(y,x); }
result = one.add (two); public void add (Vec2 other) // ^^^^ From this, the member function add does not return anything that you can put into result. With a line like: x = x + other.x; (where x is a member of "the current object" and other is the object you're adding to it), it's a dead certainty that one.Add (two) is meant to modify one rather than just use it in a calculation. So, rather than: one = list_opp_in_front.get (0); two = list_opp_in_front.get (1); result = one.add (two); you'll probably need something like: result = list_opp_in_front.get (0); two = list_opp_in_front.get (1); result.add (two);
As per your method declaration public void add(Vec2 other), you are adding two into one. Thus one itself is your result, hence there no need of return. just remove the return statement and treat one as result object.
Java: Calling a class within a for loop
I've just started learning Java, so I apologize if this question is somewhat basic, and I'm sure my code is not as clean as it could be. I've been trying to write a small quiz program that will input a list of German verbs from a txt file (verblist.txt). Each line of the text file contains five strings: the German verb (verbger), the English translation (verbeng), the praeteritum and perfekt conjugations conjugations (verbprae and verbperf) and whether it uses haben or sein as the auxiliary verb (H or S, stored as verbhaben). The verb set is chosen by generating a random number and selecting the "row" of the two dimensional array. The GUI then displays the first two variables, and the user has to input the last three. If the last three match the values in the txt file, the user gets it correct and moves on to another verb. I'm at the point where the code is working the way I want it to - for one verb. The way I've been organizing it is in two classes. One, VerbTable, imports the text file as a two dimensional array, and the other, RunVerb, generates the GUI and uses an ActionListener to compare the user input to the array. What I can't figure out now is how, after the user gets one verb set correct, I can then loop through the entire set of verbs. I was thinking of creating a for loop that loops through the number of rows in the text file (saved in the code as height), generating a new random number each time to select a different verb set (or "row" in the two dimensional array.) Essentially, I'd like to get a loop to run through the entire VerbRun class, and pause for the ActionListener, until all of the verb sets have been displayed. Here is the VerbTable class, which generates the array and random number to select the row: package looptest; import java.io.*; import java.util.*; public class VerbTable { public int width; public int height; public int randnum; public String verbger = new String(""); public String verbeng = new String(""); public String verbprae = new String(""); public String verbperf = new String(""); public String verbhaben = new String(""); public VerbTable() { File file = new File("verblist.txt"); try { /* For array height and width */ Scanner scanner1 = new Scanner(file).useDelimiter("\n"); int height = 0; int width = 0; while (scanner1.hasNextLine()) { String line = scanner1.nextLine(); height++; String[] line3 = line.split("\t"); width = line3.length; } System.out.println("Height: " + height); System.out.println("Width: " + width); this.width = width; this.height = height; /* Array height/width end */ /* random number generator */ int randnum1 = 1 + (int)(Math.random() * (height-1)); this.randnum = randnum1; /* random number generator end */ Scanner scanner = new Scanner(file).useDelimiter("\n"); String verbtable[][]; verbtable = new String[width][height]; int j = 0; while (scanner.hasNextLine()){ String verblist2 = scanner.next(); String[] verblist1 = verblist2.split("\t"); System.out.println(verblist2); verbtable[0][j] = verblist1[0]; verbtable[1][j] = verblist1[1]; verbtable[2][j] = verblist1[2]; verbtable[3][j] = verblist1[3]; verbtable[4][j] = verblist1[4]; j++; } this.verbger = verbtable[0][randnum]; this.verbeng = verbtable[1][randnum]; this.verbprae = verbtable[2][randnum]; this.verbperf = verbtable[3][randnum]; this.verbhaben = verbtable[4][randnum]; } catch (FileNotFoundException e){ e.printStackTrace(); } } public int getRand(){ return this.randnum; } public int getWidth(){ return this.width; } public int getHeight(){ return this.height; } public String getVerbger(){ return this.verbger; } public String getVerbeng(){ return this.verbeng; } public String getVerbprae(){ return this.verbprae; } public String getVerbperf(){ return this.verbperf; } public String getVerbhaben(){ return this.verbhaben; } public static void main(String[] args) throws IOException { } } And here is the RunVerb class: package looptest; import java.awt.*; import javax.swing.*; import java.awt.event.*; public class RunVerb extends JFrame { VerbTable dimensions = new VerbTable(); int width = dimensions.getWidth(); int height = dimensions.getHeight(); int randnum = dimensions.getRand(); String verbgerin = dimensions.getVerbger(); String verbengin = dimensions.getVerbeng(); String verbpraein = dimensions.getVerbprae(); String verbperfin = dimensions.getVerbperf(); String verbhabenin = dimensions.getVerbhaben(); String HabenSeinSelect = new String(""); public JTextField prae = new JTextField("",8); public JTextField perf = new JTextField("",8); public JLabel verbger = new JLabel(verbgerin); public JLabel verbeng = new JLabel(verbengin); public JRadioButton haben = new JRadioButton("Haben"); public JRadioButton sein = new JRadioButton("Sein"); public RunVerb() { JButton enter = new JButton("Enter"); enter.addActionListener(new ConvertBtnListener()); prae.addActionListener(new ConvertBtnListener()); perf.addActionListener(new ConvertBtnListener()); JPanel content = new JPanel(); content.setLayout(new FlowLayout()); content.add(verbger); verbger.setBorder(BorderFactory.createEmptyBorder(15, 20, 15, 20)); content.add(verbeng); verbeng.setBorder(BorderFactory.createEmptyBorder(15, 20, 15, 40)); content.add(new JLabel("Praeteritum:")); content.add(prae); content.add(new JLabel("Perfekt:")); content.add(perf); content.add(haben); haben.setBorder(BorderFactory.createEmptyBorder(0, 20, 0, 10)); haben.setSelected(true); content.add(sein); sein.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 10)); ButtonGroup bg = new ButtonGroup(); bg.add(haben); bg.add(sein); content.add(enter); setContentPane(content); pack(); setTitle("Verben"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); } class ConvertBtnListener implements ActionListener { public void actionPerformed(ActionEvent e) { String outprae = prae.getText(); int praenum = 0; if (outprae.equals(verbpraein)){ praenum = 1; } String outperf = perf.getText(); int perfnum = 0; if (outperf.equals(verbperfin)){ perfnum = 1; } boolean habenselect = haben.isSelected(); boolean seinselect = sein.isSelected(); if (habenselect == true){ HabenSeinSelect = "H"; } else { HabenSeinSelect = "S"; } int habennum = 0; if (HabenSeinSelect.equals(verbhabenin)) { habennum = 1; } int numtot = praenum + perfnum + habennum; if (numtot == 3){ System.out.println("Correct."); } else{ System.out.println("Incorrect."); } numtot = 0; } } public static void main(String[] args) { window.setVisible(true); } } So what would be the best way to cycle through the entire verbtable array until all of the rows have been displayed? Should I create a for loop, and if so, where should it go? Should I make a new class that contains the loop and references the VerbRun class? If so, what would be the best way to go about it? I hope this makes sense! Thank you!
To go through all the verbs exactly in a random order, you may not want to generate random numbers each time, as the random number can repeat. You have to create a random permutation of verbs, one way to do it is Collections.shuffle see http://download.oracle.com/javase/6/docs/api/java/util/Collections.html Also You dont have to create a new RunVerb Object, instead create once, and use setters to change the UI, and the functionality of Action Listeners. So pseudo code would be Collections.shuffle(verbsList); for(verb : verbsList) { setLabel1(verb[0]); setLabel2(verb[1]);... }
I would have a method like getNextRandomVerb() in then VerbTable class that generates the next verb to be shown. It will keep track of the verbs that have been shown ( for a given user-session ofcourse ) already and ensure the next one picked is not a repeat. Your RunVerb class seems to more responsible for managing the GUI , so this is not the place to define how to get the next verb to display.
sudoku game constructor
I am having trouble initializing a parameterless constructor with a defined game. Somehow it keeps on returning null if I use a getter method to return the game. Can anyone tell me what would be the best method to initialize the game? Currently I'm calling a method from within another class which has a static method but it doesn't seem to work because it gives a null value if I get the game. This is how I this game to be: {{7,8,1,0,0,4,0,0,6}, {2,0,9,3,6,0,1,0,0}, {6,0,0,0,9,0,8,0,0}, {0,0,0,0,3,5,0,0,0}, {3,5,0,0,0,0,0,1,9}, {0,0,0,4,2,0,0,0,0}, {0,0,3,0,1,0,0,0,8}, {0,0,7,0,8,3,4,0,1}, {9,0,0,6,0,0,5,7,3}}, public class SudokuPlayer { private int [][] game; public enum CellState { EMPTY, FIXED, PLAYED }; private CellState[][] gamestate; private static final int GRID_SIZE=9; public SudokuPlayer() { int[][] copy= SudokuGames.getGame(4); int size = copy.length; int[][] game = new int[GRID_SIZE][GRID_SIZE]; for ( int row = 0; row < size; row++) { for ( int col =0; col < size; col++) { game[row][col] = copy[row][col]; } } } public int[][] getGame() { return game; } } here is the method from a diferent class im calling: public class SudokuGames { public static final int [][][] GAMES = { // Game 0 VE - DEFAULT 30 squares filled {{5,3,0,0,7,0,0,0,0}, {6,0,0,1,9,5,0,0,0}, {0,9,8,0,0,0,0,6,0}, {8,0,0,0,6,0,0,0,3}, {4,0,0,8,0,3,0,0,1}, {7,0,0,0,2,0,0,0,6}, {0,6,0,0,0,0,2,8,0}, {0,0,0,4,1,9,0,0,5}, {0,0,0,0,8,0,0,7,9}}, // Game 1 VE {{8,0,1,0,3,7,0,5,6}, {0,0,0,9,0,0,0,0,7}, {6,0,3,0,1,2,0,9,0}, {0,2,0,0,0,0,7,0,3}, {3,0,0,0,2,0,0,0,9}, {1,0,9,0,0,0,0,8,0}, {0,3,0,2,7,0,4,0,1}, {7,0,0,0,0,6,0,0,0}, {5,6,0,1,9,0,3,0,8}}, // Game 2 VE {{0,9,0,0,3,0,1,4,0}, {7,0,3,0,0,4,0,0,8}, {5,0,0,6,0,7,0,2,0}, {0,7,4,5,0,2,9,0,0}, {1,0,0,0,0,0,0,0,2}, {0,0,9,1,0,8,4,6,0}, {0,5,0,7,0,9,0,0,6}, {4,0,0,2,0,0,5,0,1}, {0,8,6,0,5,0,0,7,0}}, // Game 3 VE {{0,0,9,7,3,0,5,2,6}, {0,0,5,0,2,0,8,0,0}, {6,0,8,0,0,0,0,4,7}, {0,0,0,0,0,9,0,6,2}, {0,4,0,6,0,3,0,8,0}, {8,9,0,5,0,0,0,0,0}, {2,6,0,0,0,0,1,0,8}, {0,0,7,0,1,0,6,0,0}, {9,5,1,0,6,4,2,0,0}}, // Game 4 VE {{7,8,1,0,0,4,0,0,6}, {2,0,9,3,6,0,1,0,0}, {6,0,0,0,9,0,8,0,0}, {0,0,0,0,3,5,0,0,0}, {3,5,0,0,0,0,0,1,9}, {0,0,0,4,2,0,0,0,0}, {0,0,3,0,1,0,0,0,8}, {0,0,7,0,8,3,4,0,1}, {9,0,0,6,0,0,5,7,3}}, // Game 5 E {{0,0,0,9,1,0,0,0,2}, {5,0,0,0,0,0,0,0,0}, {3,0,0,5,4,0,0,6,8}, {0,4,2,7,0,0,3,0,5}, {0,0,3,4,5,6,2,0,0}, {1,0,9,0,0,8,7,4,0}, {8,1,0,0,7,5,0,0,4}, {0,0,0,0,0,0,0,0,1}, {9,0,0,0,8,4,0,0,0}}, // Game 6 E {{0,0,0,1,0,7,0,9,0}, {0,0,0,4,9,0,3,0,0}, {6,0,0,0,3,0,4,1,0}, {4,0,5,0,0,0,0,3,0}, {8,2,0,0,0,0,0,5,4}, {0,3,0,0,0,0,2,0,6}, {0,1,4,0,7,0,0,0,5}, {0,0,8,0,2,5,0,0,0}, {0,6,0,8,0,1,0,0,0}}, // Game 7 E {{0,0,2,8,0,7,5,0,0}, {6,0,0,0,0,0,0,0,4}, {0,8,0,0,6,0,0,7,0}, {1,3,0,4,0,9,0,2,5}, {0,0,0,0,0,0,0,0,0}, {4,5,0,7,0,1,0,6,8}, {0,6,0,0,3,0,0,9,0}, {5,0,0,0,0,0,0,0,7}, {0,0,1,6,0,4,2,0,0}} }; //End /** * getGame(int gameID) returns a a Sudoku game as int [][] * as specified by the gameID. If the gameID is outside the * list of possible games, null is returned. * #param gameID number of game to be played * #return int[][] a game to be played */ public static int [][] getGame (int gameID) { /** A little dangerous. A copy of the reference to the original array * is returned. Not a copy of the array. **/ if (gameID >= 0 && gameID < GAMES.length) { return GAMES[gameID]; } else { return null; } } }
You are hiding the instance variable. Change the following int[][] game = new int[GRID_SIZE][GRID_SIZE]; to game = new int[GRID_SIZE][GRID_SIZE];