I am trying to create a "dragon curve" that uses left and right turns to create a shape on the drawing panel. The directions are generated recursively, where for a certain number of iterations or "levels" the direction adds on the previous string of turns to a single right turn plus the reverse complement of the previous string: previous string + "R" + the reverse complement of the previous string.
Based on my result, my complement method is not correctly making the reverse complement and I am not sure why. Here's is my code.
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
intro();
int level = userlevel(scan);
int size = userSize(scan);
String fileName = BASE + level + TXT;
recursion(level, fileName);
drawDragon(fileName, size, level);
}
/**
* Prints the introductory message
**/
public static void intro()
{
System.out.println("This program will generate a fractal called the Dragon Curve");
System.out.println("first explored by John Heighway, Bruce Banks, and William Harter");
System.out.println("at Nasa in teh 1960's");
}
/**
* Inputs the user's desired level for the dragon curve
* #param the Scanner object for recieving user inputs
* #return the user's desired level
**/
public static int userlevel(Scanner scan)
{
String levelPrompt = "Enter the level of the fractcal you'd like to see (1-25): ";
int level = MyUtils.getNumber(scan, levelPrompt, MINLEVEL, MAXLEVEL);
return level;
}
/**
* Inputs the user's desired drawing panel width and height
* #param the Scanner object for recieving user inputs
* #return the user's desired drawing panel size
**/
public static int userSize(Scanner scan)
{
String panelPrompt = "Enter the size of your drawing panel, in pixels (100-2000): ";
int size = MyUtils.getNumber(scan, panelPrompt, MINSIZE, MAXSIZE);
return size;
}
/**
* Creates the reverse complement of the previous dragon curve string
* #param the previous string used the in the recursive loop
* #return the new reverse complement string
**/
public static String complement(String previousString)
{
StringBuilder newString = new StringBuilder();
char letter = '\0';
for (int i=previousString.length(); i<0; i--)
{
letter = previousString.charAt(i);
if (letter == 'L')
newString.append('R');
else if (letter == 'R')
newString.append('L');
}
return newString.toString();
}
/**
* Creates the string of directions for the dragon curve using recursion
* #param level - the user's desired level
* #param fileName - the file in which the dragon curve string is located
* #return the new set of directions for the curve after each loop
**/
public static String recursion(int level, String fileName)
{
PrintStream output = MyUtils.createOutputFile(fileName);
String newDirection = "";
String directions = "";
if (level==1)
{
directions = "R";
output.print(directions);
}
else
{
String previousString = recursion(level-1, fileName);
String nextComplement = complement(previousString);
newDirection = previousString + "R" + nextComplement;
output.print(newDirection);
System.out.println(newDirection);
//output.flush();
//output.close();
}
return newDirection;
}
/**
* Draws the dragon curve on the drawing panel
* #param fileName - the file where the dragon curve directions are located
* #param size - the width and height of the drawing panel
* #param level - the user's desired level
**/
public static void drawDragon(String fileName, int size, int level)
{
Scanner fileScan = MyUtils.getFileScanner(fileName);
System.out.println("Path generated, writing to file " + fileName + "...");
String direction = fileScan.nextLine();
System.out.println("Drawing Curve...");
DragonDraw dd = new DragonDraw(size);
dd.drawCurve(fileName, level);
}
}
Here is the error: I am only getting repeated "R"'s.
Enter the level of the fractcal you'd like to see (1-25): 20
Enter the size of your drawing panel, in pixels (100-2000): 500
R
RR
RRR
RRRR
RRRRR
RRRRRR
RRRRRRR
RRRRRRRR
RRRRRRRRR
RRRRRRRRRR
RRRRRRRRRRR
RRRRRRRRRRRR
RRRRRRRRRRRRR
RRRRRRRRRRRRRR
RRRRRRRRRRRRRRR
RRRRRRRRRRRRRRRR
RRRRRRRRRRRRRRRRR
RRRRRRRRRRRRRRRRRR
RRRRRRRRRRRRRRRRRRR
Path generated, writing to file dragon20.txt...
Drawing Curve...
Thanks so much!
Take a look at your for loop inside complement method. It is running while the variable i is less than zero, this should run while this variable is greater than zero. So change this for (int i=previousString.length(); i<0; i--) to for (int i=previousString.length() - 1; i >= 0; i--) and it shall work fine.
Related
I can't get the output to print, I've tried many diff. things to try and get it to print but it won't work. It's supposed to print error messages if I put in a negative # for height or edge. Also the output for valid #'s won't print either. I'm not sure where to put the block of code for that one. Can someone help me?
My Program: https://pastebin.com/D8FQv1yR
import java.util.Scanner;
/**
*The App for the Decagonal Prism program.
* #author Kathleen Tumlin - Fundamentals of Computing I - 1210
* #version 9/17/21
*/
public class DecagonalPrismApp {
//fields
String label = "";
double edge = 0;
double height = 0;
double edgeIn = 0;
double heightIn = 0;
// constuctor
/** Shows public decagonal prism, setLabel, and setEdge.
* #param labelIn takes input for label in the constructor.
* #param edgeIn takes input for the edge in the constructor.
*/
public DecagonalPrismApp(String labelIn, double edgeIn, double heightIn) {
setLabel(labelIn);
setEdge(edgeIn);
setHeight(heightIn);
}
//methods
/** Shows the return for label variable.
* #return returns the label variable.
*/
public String getLabel() {
return label;
}
/** Shows the set label.
* #param labelIn takes the labelIn for the method.
* #return returns the boolean if the variable was set.
*/
public boolean setLabel(String labelIn) {
if (labelIn != null) {
label = labelIn.trim();
return true;
} else {
return false;
}
}
/** Shows the return for the edge variable.
* #return returns the value for the variable edge.
*/
public double getEdge() {
return edge;
}
/** Shows the set edge.
* #param edgeIn takes the edgein and sets it as the edge variable.
* #return returns the boolean if the variable was set.
*/
public boolean setEdge(double edgeIn) {
if (edgeIn > -1) {
edge = edgeIn;
return true;
}
else {
System.out.println("Error: edge must be non-negative.");
return false;
}
}
/** Shows the return for the height variable.
*#return returns the value for the variable edge.
*/
public double getHeight() {
return height;
}
/** Shows the set height.
* #param heightIn takes the heightin and sets it as the height variable.
* #return returns the boolean if the variable was set.
*/
public boolean setHeight(double heightIn) {
if (heightIn > -1) {
height = heightIn;
return true;
}
else {
System.out.println("Error: height must be non-negative.");
return false;
}
}
public void start() {
do {
System.out.print("Error: height must be non-negative." );
} while (heightIn > -1);
do {
System.out.print("Error: edge must be non-negative." );
} while (edgeIn > -1);
}
public static void main(String[] args) {
/**
*Shows what prints.
* #param args not used.
*/
Scanner scan = new Scanner(System.in);
System.out.println("Enter label, edge, and height length for a "
+ "decagonal prism.");
System.out.print("\tlabel: ");
String label = scan.nextLine();
System.out.print("\tedge: ");
double edge = scan.nextDouble();
System.out.print("\theight: ");
double height = scan.nextDouble();
}
}
Valid #'s code: https://pastebin.com/DPuSpMEq
public String toString() {
DecimalFormat fmt = new DecimalFormat("#,##0.0##");
return "A decagonal prism \"" + label
+ "with edge = " + edge + " units.\n\t"
+ "and height = " + height + " units.\n\t has:"
+ "surface area = " + fmt.format(surfaceArea()) + " square units\n\t"
+ "base area = " + fmt.format(baseArea()) + " square units \n\t"
+ "lateral surface area = "
+ fmt.format(lateralSurfaceArea()) + " square units\n\t"
+ "volume = " + fmt.format(volume()) + " cubic units \n\t";
I'm trying to print out a shape of the letter V using recursion only. I have seen some of the codes in this website related to my problem, but the majority use loops instead of recursion.
Here's my code:
public class Pattern {
public static void main(String[] args) {
printPattern(5);
}
public static void Pattern(int count, String s) {
if (count == 0) {
return;
}
System.out.print(s);
Pattern(count - 1, s);
}
public static void upperhalf(int count, int max) {
if (count == 0) {
return;
}
Pattern(max - count, " ");
Pattern(count, "* ");
System.out.println();
upperhalf(count - 1, max);
}
public static void printPattern(int n) {
upperhalf(n, n);
}
}
Output:
* * * * *
* * * *
* * *
* *
*
The output I want:
* *
* *
* *
* *
*
One way of solving it. Replace your two consecutive Pattern calls with this:
Pattern(max - count, " ");
Pattern(1, "* ");
Pattern(count - 2, " ");
Pattern(1, count > 1 ? "* " : "");
(Ie your first Pattern call, then an explicit for a single *, then a few spaces (2 less than in your approach), then the last *).
You also need to change the exit statement slightly:
public static void Pattern(int count, String s) {
if (count <= 0) { // <= instead of ==
return;
}
If your interested, here is one way to do it by by taking successive substrings.
Here are some key points.
The starting size is modified to ensure it is odd. This guarantees the V will be uniform.
The passed string consists of white space followed by an asterisk. The left asterisk is supplied by the recursive method.
The indentation is used to properly position the start of the remaining string.
int size = 10;
String v = " ".repeat((size | 1) - 2) + "*";
V(v,0);
public static void V(String v, int indent) {
System.out.println(" ".repeat(indent)+ "*" + v);
if (v.isEmpty()) {
return;
}
V(v.substring(2),indent+1);
}
trying to get areasConnected to display. As you can see I have attemped (poorly I know) to substitute this method with the nextArea method. Will post the GameWorld class below this one. Please note that I DO NOT want someone to do the work for me, just point me in the right direction.
/**
* Auto Generated Java Class.
*/
import java.util.Scanner;
public class WereWolfenstein2D {
GameWorld gameOne = new GameWorld(true);
private boolean tracing = false;
Scanner sc = new Scanner(System.in);
String input, answer, restart;
int walk, current;
char area;
public void explain() {
System.out.print("You are a hunter, defend the village and capture the Werewolf by shooting it three times. ");
System.out.println("If you get bitten visit the village to be cured. " +
"If you get bitten twice you'll turn." +
"If none of the town folk survive, you lose. " +
"Now choose how what circumstances you're willing to work in.");
}
public void pickDifficulity(){
{
System.out.println("Easy, Normal or Hard?");
input = sc.nextLine();
input = input.toUpperCase();
if (input.equals("EASY")){
System.out.println(Difficulty.EASY);
}
else if (input.equals("NORMAL")) {
System.out.println(Difficulty.NORMAL);
}
else if (input.equals("HARD")) {
System.out.println(Difficulty.HARD);
}
}
}
public void preMove(){
System.out.println("current stats");
// no. of actions until dawn
gameOne.checkForDawn();
// current population
gameOne.getVillagePopulation();
// if they can hear village
gameOne.isVillageNear();
// if not bitten:
gameOne.getShotCount();
// current area no.
gameOne.getCurrentArea();
// number of connecting areas
// gameOne.nextArea(char direction);
//gameOne.areasConnected(int s1, int s2);
// no of times werewolf shot
// no. of bullets left
gameOne.getShotCount();
// if the player can smell the wolf
gameOne.werewolfNear();
}
public void pickMove(){
System.out.print("walk shoot, quit or reset?");
answer = sc.nextLine();
//walk
//if area not connected: alert
//if into village: alert that they are healed
//if containing wolf: altert they are bitten, if already bitten game ends
switch(answer) {
case "walk": System.out.println("Pick a direction to walk in south(s), east(e), north(n), west(w)");
current = gameOne.getCurrentArea(); //current area they are in
char direction = sc.next().charAt(current); //direction they wish to travel
// char area = sc.next().charAt(current);
char area1 = 's';
char area2 = 'e';
char area3 = 'n';
char area4 = 'w';
System.out.println("the area to the south is: " + gameOne.nextArea(area1));
System.out.println("the area to the east is: " + gameOne.nextArea(area2));
System.out.println("the area to the north is: " + gameOne.nextArea(area3));
System.out.println("the area to the west is: " + gameOne.nextArea(area4));
System.out.println(current +"<< >>" + direction);
System.out.println("pick again");
int newcurrent = direction;
direction = sc.next().charAt(newcurrent);
System.out.println(newcurrent + "<< new >>" + direction);
break;
case "shoot":
break;
case "quit": System.out.print("would you like to start again? (yes/no)");
restart = sc.nextLine();
if (restart.equals("yes")) {
gameOne.reset();
}
else {
System.out.println("Thanks for playing");
}
break;
case "reset": //gameOne.reset();
this.pickDifficulity();
break;
}
}
public void play() {
this.explain();
this.pickDifficulity();
this.preMove();
this.pickMove();
// gameOne.reset();
}
public void setTracing(boolean onOff) {
tracing = onOff;
}
public void trace(String message) {
if (tracing) {
System.out.println("WereWolfenstein2D: " + message);
}
}
}
GAMEWORLD CLASS>>>
public class GameWorld {
// Final instance variables
public final int NIGHT_LENGTH = 3; // three actions until dawn arrives (day is instantaneous)
private final int MAX_SHOTS_NEEDED = 3; // successful hits required to subdue werewolf
//This map is _deliberately_ confusing, although it actually a regular layout
private int[] east = {1,2,0,4,5,3,7,8,6}; // areas to east of current location (index)
private int[] west = {2,0,1,5,3,4,8,6,7}; // areas to west of current location (index)
private int[] north = {6,7,8,0,1,2,3,4,5}; // areas to north of current location (index)
private int[] south = {3,4,5,6,7,8,0,1,2}; // areas to south of current location (index)
private int numAreas = south.length; // number of areas in the "world"
// Non-final instance variables
private int currentArea; // current location of player
private int villagePos; // area where the village is located
private int wolfPos; // area where the werewolf can be found
private Difficulty level; // difficulty level of the game
private int villagerCount; // number of villagers remaining
private int stepsUntilDawn; // number of actions until night falls
private boolean isBitten; // is the player currently bitten and in need of treatment?
private int hitsRemaining; // number of shots still needed to subdue the werewolf
private Random generator; // to use for random placement in areas
private boolean tracing; // switch for tracing messages
/**
* Creates a game world for the WereWolfenstein 2D game.
* #param traceOnOff whether or not tracing output should be shown
*/
public GameWorld(boolean traceOnOff) {
trace("GameWorld() starts...");
generator = new Random();
generator.setSeed(101); //this default setting makes the game more predictable, for testing
setTracing(traceOnOff); //this may replace random number generator
trace("...GameWorld() ends");
}
/**
* Returns the number of the current area.
* #return which area number player is within
*/
public int getCurrentArea() {
trace("getCurrentArea() starts... ...and ends with value " + currentArea);
return currentArea;
}
/**
* Returns the number of shot attempts, formatted as "total hits/total required"
* #return the fraction of shots that have hit the werewolf (out of the required number of hits)
*/
public String getShotCount() {
String count; // formatted total
trace("getShotCount() starts...");
count = (MAX_SHOTS_NEEDED - hitsRemaining) + "/" + MAX_SHOTS_NEEDED;
trace("getShotCount() ...ends with value " + count);
return count;
}
/**
* Returns the current number of villagers.
* #return the villager count, >= 0
*/
public int getVillagePopulation() {
return villagerCount;
}
/**
* Returns the number of actions remaining until dawn arrives.
* #return actions remaining until dawn event
*/
public int getActionsUntilNight() {
return stepsUntilDawn;
}
/**
* Randomly determines a unique starting location (currentArea), village
* position (villagePos) and werewolf position (wolfPos).
* #param difficulty - the difficulty level of the game
* #return the starting location (area)
*/
public int newGame(Difficulty difficulty) {
trace("newGame() starts...");
level = difficulty;
//determine village location and initialise villagers and night length
villagePos = generator.nextInt(numAreas);
stepsUntilDawn = NIGHT_LENGTH;
villagerCount = level.getVillagerCount();
// determine player's position
if (level.getPlayerStartsInVillage()) {
//place player in village
currentArea = villagePos;
} else {
//pick a random location for player away from the village
do {
currentArea = generator.nextInt(numAreas);
} while (currentArea == villagePos);
}
trace("player starts at " + currentArea);
// determine werewolf's position
trace("calling resetTargetPosition()");
resetWolfPosition();
// define player's status
trace("player is not bitten");
isBitten = false;
trace("werewolf is not hit");
hitsRemaining = MAX_SHOTS_NEEDED;
trace("...newGame() ends with value " + currentArea);
return currentArea;
}
/** Randomly determines a unique location for werewolf (wolfPos). */
private void resetWolfPosition() {
int pos; // werewolf position
trace("resetWolfPosition() starts...");
pos = generator.nextInt(numAreas);
while (pos == currentArea || pos == villagePos) {
trace("clash detected");
// avoid clash with current location
pos = generator.nextInt(numAreas);
}
wolfPos = pos;
trace("werewolf position is " + wolfPos);
trace("...resetWolfPosition() ends");
}
/**
* Returns the nearness of the werewolf.
* #return Status of werewolf's location
* BITTEN: if player is currently bitten (and delirious)
* NEAR: if werewolf is in a connected area
* FAR: if werewolf is elsewhere
*/
public Result werewolfNear() {
trace("werewolfNear() starts");
if (isBitten) {
trace("werewolfNear(): player is still delirious from a bite so cannot sense nearness of werewolf");
return Result.BITTEN;
}
trace("werewolfNear() returning result of nearnessTo(" + wolfPos + ")");
return nearnessTo(wolfPos);
}
/**
* Returns true if the village is near the player (in an adjacent area),
* false otherwise.
* #return true if the player is near (but not in) the village, false otherwise.
*/
public boolean isVillageNear() {
trace("villageNear() starts and returns result of nearnessTo(" + villagePos + ") == Result.NEAR");
return nearnessTo(villagePos) == Result.NEAR;
}
/**
* Returns the nearness of the player to the nominated area.
* #param area the area (werewolf or village) to assess
* #return Nearness of player to nominated area
* NEAR: if player is adjacent to area
* FAR: if player is not adjacent to the area
*/
private Result nearnessTo(int area) {
Result closeness; // closeness of player to area
trace("nearnessTo() starts...");
if ((east[currentArea] == area) ||
(west[currentArea] == area) ||
(north[currentArea] == area) ||
(south[currentArea] == area))
{
// player is close to area
closeness = Result.NEAR;
trace("area is close");
} else {
// player is not adjacent to area
closeness = Result.FAR;
trace("area is far");
}
trace("...nearnessTo() ends with value " + closeness);
return closeness;
}
/**
* Try to move the player to another area. If the move is not IMPOSSIBLE
* then the number of actions remaining before dawn arrives is decremented.
* #param into the area to try to move into
* #return Result of the movement attempt
* SUCCESS: move was successful (current position changed)
* VILLAGE: move was successful and player has arrived in the village (and is not longer bitten)
* BITTEN: move was successful but player encountered the werewolf
* FAILURE: move was successful but already bitten player encountered the werewolf again
* IMPOSSIBLE: move was impossible (current position not changed)
*/
public Result tryWalk(int into) {
Result result; // outcome of walk attempt
trace("tryWalk() starts...");
if (areasConnected(currentArea, into)) {
trace("move into area " + into );
currentArea = into;
if (currentArea != wolfPos) {
// werewolf not found
trace("werewolf not encountered");
result = Result.SUCCESS;
if (currentArea == villagePos) {
isBitten = false;
result = Result.VILLAGE;
}
} else {
// werewolf encountered
if (isBitten) {
trace("werewolf encountered again");
result = Result.FAILURE;
} else {
// not bitten
trace("werewolf encountered");
result = Result.BITTEN;
isBitten = true;
resetWolfPosition();
}
}
stepsUntilDawn--; //one more action taken
} else { // area not connected
trace("move not possible");
result = Result.IMPOSSIBLE;
}
trace("...tryWalk() ends with value " + result);
return result;
}
/**
* Try to shoot a silver bullet at the werewolf from the current area.
* If the shot is not IMPOSSIBLE then the number of actions remaining
* before dawn arrives is decremented.
* #param into the area to attempt to shoot into
* #return status of attempt
* CAPTURED: werewolf has been subdued and captured
* SUCCESS: werewolf has been hit but is not yet captured
* VILLAGE: the shot went into the village and a villager has died
* FAILURE: werewolf not present
* IMPOSSIBLE: area not connected
*/
public Result shoot(int into) {
Result result; // outcome of shooting attempt
trace("shoot() starts...");
if (areasConnected(currentArea, into)) {
// area connected
trace("shoot into area " + into );
if (into == villagePos) {
result = Result.VILLAGE;
villagerCount--;
trace("shot into village");
} else if (into != wolfPos) {
// not at werewolf location (but at least didn't shoot into the village!)
result = Result.FAILURE;
trace("werewolf not present");
} else {
// at werewolf location
hitsRemaining--;
if (hitsRemaining == 0) {
// last hit required to subdue the werewolf
trace("werewolf subdued and captured");
result = Result.CAPTURED;
} else {
// not the last shot
result = Result.SUCCESS;
if (level.getWolfMovesWhenShot()) {
resetWolfPosition();
}
trace("werewolf found but not yet captured");
}
}
stepsUntilDawn--; //one more action taken
} else {
// not at valid location
result = Result.IMPOSSIBLE;
trace("area not present");
}
trace("...shoot() ends with value " + result);
return result;
}
/**
* Checks if there are no more actions left until dawn arrives. If dawn is
* here then decrements the number of villagers, repositions the werewolf
* and resets the number of actions until dawn arrives again. Returns true
* if dawn occurred, false if it did not.
* #return true if dawn just happened, false if has not yet arrived
*/
public boolean checkForDawn() {
if (stepsUntilDawn == 0) {
if (villagerCount > 0) { //dawn may arrive after shooting the last villager
villagerCount--;
}
stepsUntilDawn = NIGHT_LENGTH;
resetWolfPosition();
return true;
}
return false;
}
/**
* Returns true if areas s1 and s2 are connected, false otherwise.
* Also returns false if either area is an invalid area identifier.
* #param s1 the first area
* #param s2 the second area
* #return true if areas are connected, false otherwise
*/
private boolean areasConnected(int s1, int s2) {
if (Math.min(s1, s2) >= 0 && Math.max(s1, s2) < numAreas) { //valid areas...
//...but are they connected?
return east[s1] == s2 || north[s1] == s2 || west[s1] == s2 || south[s1] == s2;
}
//Either s1 or s2 is not a valid area identifier
return false;
}
/**
* Determine ID number of an adjacent area given its direction from the
* current area.
* #param direction the direction to look (n for north, e for east, s for south, w for west)
* #return number of the area in that direction
* #throws IllegalArgumentException if direction is null
*/
public int nextArea(char direction) {
int nextIs; // area number of area in indicated direction
//Valid values
final char N = 'n', E = 'e', S = 's', W = 'w';
trace("nextArea() starts...");
// examine adjacent areas
switch (direction) {
case N: trace("determining number of area to the north");
nextIs = north[currentArea];
break;
case E: trace("determining number of area to the east");
nextIs = east[currentArea];
break;
case S: trace("determining number of area to the south");
nextIs = south[currentArea];
break;
case W: trace("determining number of area to the west");
nextIs = west[currentArea];
break;
default: throw new IllegalArgumentException("Direction must be one of " + N + ", " + E + ", " + S + " or " + W);
}
trace("...nextArea() ends with value for '" + direction + "' of " + nextIs);
return nextIs;
}
/** Resets all game values. */
public void reset() {
trace("reset() starts...");
// reset all game values
trace("resetting all game values");
newGame(level); //start a new game with the same difficulty
trace("...reset() ends");
}
/**
* Turn tracing messages on or off. If off then it is assumed that
* debugging is not occurring and so a new (unseeded) random number
* generator is created so the game is unpredictable.
* #param shouldTrace indicates if tracing messages should be displayed or not
*/
public void setTracing(boolean shouldTrace) {
if (! shouldTrace) { // not tracing so get an unseeded RNG
generator = new Random();
}
tracing = shouldTrace;
}
/**
* Prints the given tracing message if tracing is enabled.
* #param message the message to be displayed
*/
public void trace(String message) {
if (tracing) {
System.out.println("GameWorld: " + message);
}
}
}
You can use reflection. Actually, it's the only way out if you want to directly access the private methods/fields of an object or a class.
The loop in the following code stops after the first element:
public ArrayList<Position> moveOptions(Player p, Die d)
{
// Init array
ArrayList<Position> options = new ArrayList<>();
Helper.m("Option size: " + options.size());
// Get player's pin positions (current)
ArrayList<Position> pos = p.getPinPositions();
Helper.m("p.getPinPositions() size: " + pos.size());
int i = 0;
for (Position ps : p.getPinPositions()) {
Helper.m("I am in the loop");
// Get the pin in this position
Pin pin = ps.getPin();
// Get next field according to the die
Helper.m("The size of pos before 'next' call:" + pos.size());
Field next = ps.getPin().getNextFieldByDie(d);
Helper.m("The size of pos after 'next' call:" + pos.size());
// If the die value doesn't exceed the board size
if(next != null)
{
Helper.m("next is not null");
Helper.m("The size of pos before constructor call:" + pos.size());
Position possible = new Position(next, ps.getPin());
Helper.m("The size of pos after constructor call:" + pos.size());
options.add(possible);
}
Helper.m("The size of 'options' is now " + options.size());
i++;
}
Helper.m("I: " + i);
Helper.m("The final size of 'options' is " + options.size());
Helper.m("The final size of 'pos' is " + pos.size());
return options;
}
After some investigation I got to the conclusion that this line is the issue:
Position possible = new Position(next, ps.getPin());
The loop doesn't continue even if I put a 'continue' there or if I create a new empty instance of the Position outside the loop. Any suggestions?
The output is this:
Option size: 0
p.getPinPositions() size: 4
I am in the loop
The size of pos before 'next' call:4
The size of pos after 'next' call:1
next is not null
The size of pos before constructor call:1
The size of pos after constructor call:1
The size of 'options' is now 1
I: 1
The final size of 'options' is 1
The final size of 'pos' is 1
The Position class:
/**
* Keep pin positions in object
*/
public class Position {
// Field object
private Field field;
// Pin Object
private Pin pin;
public Position(){};
/**
* Constructor
* #param f Field object
* #param p Pin Object
*/
public Position(Field f, Pin p)
{
this.setFeild(f);
this.setPin(p);
}
/**
* Field setter
* #param f
*/
public final void setFeild(Field f)
{
this.field = f;
}
/**
* Field getter
* #return
*/
public Field getField()
{
return this.field;
}
/**
* Pin setter
* #param p
*/
public final void setPin(Pin p)
{
this.pin = p;
}
/**
* Pin getter
* #return
*/
public Pin getPin()
{
return this.pin;
}
}
Thank you!
This problem is caused in your Pin class in your getCurrentField() method which is called when you call getNextFieldByDie(Die die) from your loop. The problem is that you are removing items from the iterator that are not equivalent to the current pin. This action doesn't just produce an ArrayList with the elements you are interested in, it actually modifies the backing store which in your code is in the GameManager class.
public Field getCurrentField()
{
ArrayList<Position> positions = this.getManager().getPinPositions();
for (Iterator<Position> it=positions.iterator(); it.hasNext();) {
if (!it.next().getPin().equals(this))
it.remove();
}
if(positions.size() > 0)
return positions.get(0).getField();
else
return null;
}
After calling it.remove() on the Position objects that meet your criteria, your pos list (which is drawn from the same instance of the GameManager class) will no longer have anything but the original item left in it. Hence the change of size.
Rather than removing items from the iterator, it would be better to create a new ArrayList that contained the elements of interest.
public Field getCurrentField()
{
ArrayList<Position> positions = this.getManager().getPinPositions();
//Just create a new list
ArrayList<Position> matchedPositions = new ArrayList<Position>();
//Use the for-each syntax to iterate over the iterator
for (Position position : positions) {
//switch the logic and add to the new list
if (position.getPin().equals(this))
matchedPositions.add(position);
}
if(matchedPositions.size() > 0)
return matchedPositions.get(0).getField();
else
return null;
}
I also want to point out that you have this same pattern occurring in multiple places in the code base you posted, and all of them could cause similar problems and should likely be switched.
It also just happens that you were using the only method for modifying a list while iterating over that list that will not throw the ConcurrentModificationException making it harder to detect that a change had been made in your original list.
I have two textfield in my swing component. In one text field i need to have only numbers
(no string,empty spaces,special charaters allowed) and in another textfield i need to have only string(no numbers,empty spaces,special charaters allowed). How can i implement that..???
You can use the Pattern Class (Regular Expressions) to validate the input. A short tutorial is available here.
I am pretty sure that the basic tutorial covers all this...
"^//d+$" //The text must have at least one digit, no other characters are allowed
"^[a-zA-Z]+$" //The text must have at least one letter, no other characters are allowed
You have two choices, you can validate the text in the fields either 1) on entry or 2) when the user performs an action such as clicks a confirmation button.
For 2) npinti's answer should steer you in the right direction, just get the value of the field and validate it with a regular expression.
For 1) you might want to write a KeyListener that intercepts key presses and only allows the correct type of character for the field.
You can extend javax.swing.text.PlainDocument class, and call setDocument method textfield. Here is one of the example ;
package textfield;
import java.awt.Toolkit;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
public class LimitedValuePositiveIntegerDocument extends PlainDocument {
int maxValue;
int maxLength;
Toolkit toolkit;
/**
* Constructor for the class.
* #param max maximum value of the number
*/
public LimitedValuePositiveIntegerDocument(int max){
maxValue = max;
maxLength = (""+max).length();
toolkit = Toolkit.getDefaultToolkit();
}
/**
* Inserts the input string to the current string after validation.
* #param offs offset of the place where the input string is supposed to be inserted.
* #param str input string to be inserted
* #param a attribute set
*/
#Override
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException {
if(str == null)return;
String currentText = getText(0,getLength());
String resultText = new String();
int i;
boolean errorFound = false;
boolean deleteFirstZero = false;
int accepted=0;
for (i = 0; (i<str.length())&&(!errorFound); i++) {
if (Character.isDigit(str.charAt(i))) { /* if it is digit */
if (offs==currentText.length()) { /* calculates the resultant string*/
resultText = currentText+str.substring(0,i+1);
} else if (offs==0) {
resultText = str.substring(0,i+1)+currentText;
} else {
resultText = currentText.substring(0, offs)+str.substring(0,i+1)+currentText.substring(offs,currentText.length());
}
if (Integer.parseInt(resultText) > maxValue) {
errorFound = true;
toolkit.beep();
} else {
if ( resultText.length() == maxLength+1) {
deleteFirstZero = true;
}
accepted++;
}
} else {
errorFound = true;
toolkit.beep();
}
}
if ( accepted>0 ) { /* insert string */
super.insertString(offs, str.substring(0,accepted), a);
if (deleteFirstZero) {
super.remove(0,1);
}
}
}
/**
* Removes a part of the current string.
* #param offs offset of the place to be removed.
* #param len length to be removed
*/
#Override
public void remove(int offs, int len) throws BadLocationException{
super.remove(offs, len);
}
/**
* Returns max value of the number.
* #return max value
*/
public int getMaxValue() {
return maxValue;
}
/**
* Sets max value of the number.
* #param max maximum value of the number
*/
public void setMaxValue(int max) {
this.maxValue = max;
}
} // end of class
EDIT :
and its usage;
LimitedValuePositiveIntegerDocument doc = new LimitedValuePositiveIntegerDocument(999);
JTextField numberField = new JtextField();
numberField.setDocument(doc);
You can only enter positive numbers less than 1000, and it check while you are pressing the key..