Not understandable nullpointer exception - java - java

I have a nullpointer exception I cannot seem to solve, I'd love for you guys to take a look.
This is the exception I'm receiving:
java.lang.NullPointerException
at org.ikov.engine.task.impl.PlayerUpdateTask.execute(PlayerUpdateTask.java:84)
at org.ikov.engine.task.ParallelTask$1.run(ParallelTask.java:44)
at org.ikov.engine.GameEngine$4.run(GameEngine.java:160)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Line 84 of PlayerUpdateTask is:
for (int other : localPlayerList) {
The code up to there is
if(player.getLocalPlayers() == null) {
player.disconnected = true;
return;
}
List<Integer> localPlayerList = new ArrayList<Integer>(player.getLocalPlayers());
/*
* If the map region changed send the new one. We do this immediately as
* the client can begin loading it before the actual packet is received.
*/
if (player.mapRegionDidChange) {
player.getActionSender().sendMapRegion();
}
/*
* The update block packet holds update blocks and is send after the
* main packet.
*/
GamePacketBuilder updateBlock = new GamePacketBuilder();
/*
* The main packet is written in bits instead of bytes and holds
* information about the local list, players to add and remove, movement
* and which updates are required.
*/
GamePacketBuilder packet = new GamePacketBuilder(81,
GamePacket.Type.VARIABLE_SHORT);
packet.startBitAccess();
/*
* Updates this player.
*/
updateThisPlayerMovement(packet);
updatePlayer(updateBlock, player, false, true);
/*
* Write the current size of the player list.
*/
packet.putBits(8, localPlayerList.size());
//Set up a deletion queue
List<Integer> deletionQueue = new ArrayList<Integer>();
/*
* Iterate through the local player list.
*/ - FROM HERE THE NULLPOINTER starts
Please note: the nullpointer does not always happen, it happens once in a while but I'd like to sort it out.
Do you guys have any idea, I do not understand how localPlayerList can be null considering I initialize it earlier in the method. This is for a java game, by the way.
Here's how the local player list is populated:
//We keep track of the amount of players we've added, we want to keep it down a bit as we don't want to loverload people's client
int addedPlayers = 0;
/*
* Loop through every player.
*/
for (Player otherPlayer : PlayerManager.getSingleton().getPlayers()) {
if (otherPlayer == null) {
continue;
}
if (!player.activatedPlayerUpdate) {
break;
}
if (!player.withinDistance(otherPlayer)) {
/*
* Check that the Player is within good distance of the player
* before adding to local list.
*/
continue;
}
/*
* Check if there is room left in the local list.
*/
if (player.getLocalPlayers().size() >= 255 || addedPlayers >= 20) {
/*
* There is no more room left in the local list. We cannot add
* more players, so we just ignore the extra ones. They will be
* added as other players get removed.
*/
break;
}
/*
* Do not add anymore data to the packet if it the packet exceeds
* the maximum packet size as this will cause the client to crash.
*/
if (packet.getLength() + updateBlock.getLength() >= 3072) {
break;
}
/*
* If they should not be added ignore them.
*/
if (otherPlayer == player
|| player.getLocalPlayers()
.contains(otherPlayer.getIndex())
|| !otherPlayer.isVisible()
|| otherPlayer.getMapInstance() != player.getMapInstance()) {
continue;
}
/*
* Add the player to the local list if it is within distance.
*/
player.getLocalPlayers().add(otherPlayer.getIndex());
addedPlayers++;
/*
* Add the player in the packet.
*/
addNewPlayer(packet, otherPlayer);
/*
* Update the player, forcing the appearance flag.
*/
updatePlayer(updateBlock, otherPlayer, true, false);
}
/*
* Check if the update block is not empty.
*/
if (!updateBlock.isEmpty()) {
/*
* Write a magic id indicating an update block follows.
*/
packet.putBits(11, 2047);
packet.finishBitAccess();
/*
* Add the update block at the end of this packet.
*/
packet.put(updateBlock.toPacket().getPayload());
} else {
/*
* Terminate the packet normally.
*/
packet.finishBitAccess();
}
/*
* Write the packet.
*/
player.write(packet.toPacket());
Thanks alot,
David

for (int other : localPlayerList) {
The likely reason is that localPlayerList contains an Integer that is null, and you are getting an NPE during the automatic unboxing to int.

Try to test if "localPlayerList" is null just before the "for". I don't know "getLocalPlayers()" method implementation, but is possible that return to you different results in different times? Is that method thread-safe?

Related

Is this MVC method a good way to program a Sudoku Game?

I'm building a Sudoku Game. I came here to get some help because I'm completely stuck in my code. I'm not asking for you to complete my code, I know that's not your job. Just few hints as what to do next would be great!
I use MVC and Swing Components for GUI to make the code lighter. I divided each field and method so I can understand what to do next but I'm confused. I'm particularly having trouble understanding how to do the following methods:
initializeGrid
chooseGameDifficulty
makeMove
cancelMove
Model
public class GameSudokuModel {
// states -- fields
Scanner userInput = new Scanner (System.in); // accept user input
// int levelDifficulty = 0; // level of difficulties
int [] gridSize ; // Sudoku 9x9 == 81 cells -- used to initialize grid or solve puzzle --
int [] subGridSize ; // a sub-grid = 9 cells
int gameMove = 0; // calculate the total number of moves per game // ++makeMove and --cancelMove
int [] gameCell = {1, 2, 3, 4, 5, 6, 7, 8, 9}; // a cell contain a list of choices numbers 1-9
int currentGameTime = 0; // calculates the total time to complete a puzzle
String currentPlayerName = userInput.nextLine(); // player name
// end of fields
//behaviors -- methods
/******************************************************
*
* Method calculateGameTime (initialiserGrille)
*
*
* Calculates time
*
* The stopwatch starts when the player makes ​​his first move
*
*
*
******************************************************/
public class calculateGameTime{
}
/******************************************************
*
* Method initializeGrid (initialiserGrille)
*
*
* Used to initialize a grid
*
* Reset the grid ( back to the original Sudoku grid ) using the list of moves .
*
*
*
*
*
******************************************************/
public class initializeGrid {
}
/******************************************************
*
* Method levelDifficulty
*
*
* Established the parameters of level of difficulty
*
*
* #param beginner
* #param expert
* #return
******************************************************/
public int levelDifficulty (int beginner, int expert){
while(true)
{
int levelDifficulty = 0;
levelDifficulty= userInput.nextInt();
System.out.println (" ");
if(levelDifficulty < beginner || levelDifficulty> expert){
System.out.print (" You must choose 1, 2 or 3." + "Please try again : ");
System.out.println (" ");
}
else
return levelDifficulty;
}
}
/****************************************************
* Method chooseGameDifficulty (chosisirNiveauDifficulte)
*
* The method makes possible to choose the level of complexity of a grid
*
* (1) beginner: the player starts the game with a grid made ​​up to 75% (81 * 0.75)
*
* (2) Intermediate : the player starts the game with a grid made ​​up to 50% (81 * 0.50)
*
* (3) Expert : the player starts the game with a grid made ​​up to 25% (81 * 0.25)
*
* Numbers are set randomly on the grid every new game
*
* #param beginner
* #param intermediate
* #param expert
******************************************************/
public void chooseGameDifficulty(int beginner, int intermediate, int expert){
boolean entreeValide;
int levelDifficulty;
String reponse;
levelDifficulty= levelDifficulty(beginner,expert); // call function levelDifficulty()
if(levelDifficulty==beginner)
//get easy level grid (getter)
//set easy level grid (setter)
if(levelDifficulty==intermediate)
//get intermediate level grid (getter)
//set intermediate level grid (setter)
if(levelDifficulty==expert)
//get expert level grid (getter)
//set easy expert grid (setter)
}
/****************************************************
* Method solvePuzzle (resoudrePuzzle)
*
* This method makes possible to solve the entire grid meaning all the 81 cells
*
******************************************************/
public class solvePuzzle {
}
/****************************************************
* Method makeMove (fairePlacement)
*
* Save a record of the player's actions on the grid.
*
*
*
* (1) make move on the grid ;
* (2) save moves in an array list
*
******************************************************/
public class makeMove {
//choose a cell , enter a number on the cell and confirm the selection
// adds move to the array list
int makeMove = gameMove++;
}
/****************************************************
* Method cancelMove (annulerPlacement)
*
*
*
* (1) retrieve the last instance in the arraylist (using the remove method and the size method to determine the number of elements )
* (2) cancel the move in the grid.
*
******************************************************/
public class cancelMove {
//choose a cell , remove the number on the cell and confirm the cancellation
//substracts move from array list
int cancelMove = gameMove--;
}
}
initializeGrid and chooseGameDifficulty aren't really features of the model. The model maintains the current state of the data and the rules uses to manage it.
Technically, these features should be functions of some kind of factory that given a difficult level will return a instance of the model
public class SudokuFactory {
public enum Difficulty {
HARD,
MODERATE,
EASY
}
public SudokuModel createModel(Difficulty difficult) {
// Make a new model based on the rules for your difficulty
// settings
}
}
The model would then simply contain the information and functionality to manage it
You should also avoid static where practically possible, it should never be used as a cross class communication mechanism, if you need to share data, you should pass it. static just makes the whole thing a lot more difficult to manage and debug
The view would get the information from the user (like the difficulty level), which would be used by the controller to build a new model. The model would then be passed to a new controller, which would generate a new view, which should present the current state of the model.
The controller would then respond to changes in the view, updating the model and the controller would respond to changes in the model and update the view.
You should also prefer using interfaces over implementation
So, based on my (rather pathetic) understanding of Sudoku you could use a model as simple as ...
public interface SudokuModel {
public void setValueAt(int value, int row, int col) throws IllegalArgumentException;
public int getValueAt(int row, int col);
}
Now, me, personally, I'd have an implementation that had two buffers, one which represents the actual game/solution and one which represents the player data (pre-filled based on the difficulty level), now you could have a single buffer, but you'd have constantly scan the grid to see if the new value was valid and I'm just too lazy ;)

Query on clarification about toOcean() method

This query can be answered only after going through the history of previous query where the Part I of the solution is discussed.
Following is the solution, I wrote for Part IIa and PartIIb, I need clarification before writing PartIIc i.e., toOcean() method.
/* RunLengthEncoding.java */
package Project1;
/**
* The RunLengthEncoding class defines an object that run-length encodes an
* Ocean object. Descriptions of the methods you must implement appear below.
* They include constructors of the form
*
* public RunLengthEncoding(int i, int j, int starveTime);
* public RunLengthEncoding(int i, int j, int starveTime,
* int[] runTypes, int[] runLengths) {
* public RunLengthEncoding(Ocean ocean) {
*
* that create a run-length encoding of an Ocean having width i and height j,
* in which sharks starve after starveTime timesteps.
*
* The first constructor creates a run-length encoding of an Ocean in which
* every cell is empty. The second constructor creates a run-length encoding
* for which the runs are provided as parameters. The third constructor
* converts an Ocean object into a run-length encoding of that object.
*
* See the README file accompanying this project for additional details.
*/
class RunLengthEncoding {
/**
* Define any variables associated with a RunLengthEncoding object here.
* These variables MUST be private.
*/
private DList2 list;
private int sizeOfRun;
private int width;
private int height;
private int starveTime;
/**
* The following methods are required for Part II.
*/
/**
* RunLengthEncoding() (with three parameters) is a constructor that creates
* a run-length encoding of an empty ocean having width i and height j,
* in which sharks starve after starveTime timesteps.
* #param i is the width of the ocean.
* #param j is the height of the ocean.
* #param starveTime is the number of timesteps sharks survive without food.
*/
public RunLengthEncoding(int i, int j, int starveTime) {
this.list = new DList2();
this.list.insertFront(TypeAndSize.Species.EMPTY, i*j);
this.sizeOfRun = 1;
this.width = i;
this.height = j;
this.starveTime = starveTime;
}
/**
* RunLengthEncoding() (with five parameters) is a constructor that creates
* a run-length encoding of an ocean having width i and height j, in which
* sharks starve after starveTime timesteps. The runs of the run-length
* encoding are taken from two input arrays. Run i has length runLengths[i]
* and species runTypes[i].
* #param i is the width of the ocean.
* #param j is the height of the ocean.
* #param starveTime is the number of timesteps sharks survive without food.
* #param runTypes is an array that represents the species represented by
* each run. Each element of runTypes is Ocean.EMPTY, Ocean.FISH,
* or Ocean.SHARK. Any run of sharks is treated as a run of newborn
* sharks (which are equivalent to sharks that have just eaten).
* #param runLengths is an array that represents the length of each run.
* The sum of all elements of the runLengths array should be i * j.
*/
public RunLengthEncoding(int i, int j, int starveTime,
TypeAndSize.Species[] runTypes, int[] runLengths) {
this.list = new DList2();
this.sizeOfRun = 0;
this.width = i;
this.height = j;
this.starveTime = starveTime;
if(runTypes.length != runLengths.length){
System.out.println("lengths are unequal");
}else{
for(int index=0; index < runTypes.length; index++){
this.list.insertFront(runTypes[index], runLengths[index]);
this.sizeOfRun++;
}
}
}
/**
* restartRuns() and nextRun() are two methods that work together to return
* all the runs in the run-length encoding, one by one. Each time
* nextRun() is invoked, it returns a different run (represented as a
* TypeAndSize object), until every run has been returned. The first time
* nextRun() is invoked, it returns the first run in the encoding, which
* contains cell (0, 0). After every run has been returned, nextRun()
* returns null, which lets the calling program know that there are no more
* runs in the encoding.
*
* The restartRuns() method resets the enumeration, so that nextRun() will
* once again enumerate all the runs as if nextRun() were being invoked for
* the first time.
*
* (Note: Don't worry about what might happen if nextRun() is interleaved
* with addFish() or addShark(); it won't happen.)
*/
/**
* restartRuns() resets the enumeration as described above, so that
* nextRun() will enumerate all the runs from the beginning.
*/
public void restartRuns() {
this.sizeOfRun = 0;
}
/**
* nextRun() returns the next run in the enumeration, as described above.
* If the runs have been exhausted, it returns null. The return value is
* a TypeAndSize object, which is nothing more than a way to return two
* integers at once.
* #return the next run in the enumeration, represented by a TypeAndSize
* object.
*/
public TypeAndSize nextRun() {
TypeAndSize obj = null;
if(this.sizeOfRun > 0){
obj = this.list.nTh(this.sizeOfRun);
this.sizeOfRun--;
}
return obj;
}
}
==========
/* DList2.java */
package Project1;
/**
* A DList2 is a mutable doubly-linked list. Its implementation is
* circularly-linked and employs a sentinel (dummy) node at the sentinel
* of the list.
*/
class DList2 {
/**
* sentinel references the sentinel node.
*
* DO NOT CHANGE THE FOLLOWING FIELD DECLARATIONS.
*/
protected DListNode2 sentinel;
protected long size;
/* DList2 invariants:
* 1) sentinel != null.
* 2) For any DListNode2 x in a DList2, x.next != null.
* 3) For any DListNode2 x in a DList2, x.prev != null.
* 4) For any DListNode2 x in a DList2, if x.next == y, then y.prev == x.
* 5) For any DListNode2 x in a DList2, if x.prev == y, then y.next == x.
* 6) size is the number of DListNode2s, NOT COUNTING the sentinel
* (denoted by "sentinel"), that can be accessed from the sentinel by
* a sequence of "next" references.
*/
/**
* DList2() constructor for an empty DList2.
*/
public DList2() {
this.sentinel = new DListNode2();
this.sentinel.next = this.sentinel;
this.sentinel.prev = this.sentinel;
this.size = 0;
}
/**
* insertFront() inserts an object of type TypeAndSizeAndHungerAndStarveTime at the front of a DList2.
*/
void insertFront(TypeAndSize.Species runType, int runLength) {
DListNode2 newNode = new DListNode2(runType, runLength);
newNode.next = this.sentinel.next;
this.sentinel.next.prev = newNode;
this.sentinel.next = newNode;
this.sentinel.next.prev = this.sentinel;
this.size++;
}
/**
* nTh() returns the nTh node
* #param nTh
* #return
*/
TypeAndSize nTh(int nTh){
DListNode2 node = this.sentinel.prev;
int index = 1;
while(index < nTh ){
node = node.prev;
}
return node.runObject;
}
}
============================
/* DListNode2.java */
package Project1;
/**
* A DListNode2 is a node in a DList2 (doubly-linked list).
*/
class DListNode2 {
/**
* item references the item stored in the current node.
* prev references the previous node in the DList.
* next references the next node in the DList.
*
* DO NOT CHANGE THE FOLLOWING FIELD DECLARATIONS.
*/
TypeAndSize runObject;
DListNode2 prev;
DListNode2 next;
/**
* DListNode2() constructor.
*/
DListNode2() {
this.runObject = null;
this.prev = null;
this.next = null;
}
DListNode2(TypeAndSize.Species runType, int runLength) {
this.runObject = new TypeAndSize(runType, runLength);
this.prev = null;
this.next = null;
}
}
===================================
/* TypeAndSize.java */
/* DO NOT CHANGE THIS FILE. */
/* YOUR SUBMISSION MUST WORK CORRECTLY WITH _OUR_ COPY OF THIS FILE. */
package Project1;
/**
* Each TypeAndSize object represents a sequence of identical sharks, fish,
* or empty cells. TypeAndSizes are your way of telling the test program
* what runs appear in your run-length encoding. TypeAndSizes exist solely
* so that your program can return two integers at once: one representing
* the type (species) of a run, and the other representing the size of a run.
*
* TypeAndSize objects are not appropriate for representing your run-length
* encoding, because they do not represent the degree of hunger of a run of
* sharks.
*
* #author Jonathan Shewchuk
*/
class TypeAndSize {
Species type; // runType EMPTY, SHARK, or FISH
int size; // Number of cells in the run for that runType.
enum Species{EMPTY,SHARK,FISH}
/**
* Constructor for a TypeAndSize of specified species and run length.
* #param species is Ocean.EMPTY, Ocean.SHARK, or Ocean.FISH.
* #param runLength is the number of identical cells in this run.
* #return the newly constructed Critter.
*/
TypeAndSize(Species species, int runLength) {
if (species == null) {
System.out.println("TypeAndSize Error: Illegal species.");
System.exit(1);
}
if (runLength < 1) {
System.out.println("TypeAndSize Error: runLength must be at least 1.");
System.exit(1);
}
this.type = species;
this.size = runLength;
}
}
======================================
For reference, complete skeleton of code for assignment is given in link
In the given link, following paragraph says:
Part II(c): Implement a toOcean() method in the RunLengthEncoding class, which converts a run-length encoding to an Ocean object. To accomplish this, you will need to implement a new addShark() method in the Ocean class, so that you can specify the hunger of each shark you add to the ocean. This way, you can convert an Ocean to a run-length encoding and back again without forgetting how hungry each shark was.
My question:
In PartIIa and PartIIb of the solution written in RunLenghtEncoding() 5 argument constructor, I am not capturing hungerLevel property of Shark due to the reason mentioned in method comments -
Any run of sharks is treated as a run of newborn sharks (which are equivalent to sharks that have just eaten).
I would like to know, What exactly toOcean() method mean, when. i do not capture hungerLevel of Shark runType. Am I suppose to convert the Compressed form of Ocean to an 'existing Ocean' or 'new Ocean'? Please help me, am stuck here.
Note: This is self learning course published in 2006. No mentor available for this course. Also suggest me, if this is the right place to discuss such queries
It says that
Any run of sharks is treated as a run of newborn sharks (which are equivalent to sharks that have just eaten).
So when you have to re-create the Ocean, you can treat any run of sharks as sharks with hungerLevel 0. In Part III you do have to keep track of the hungerLevel, however. But for Part II c they leave that out for the moment being.

Optimising Code an Array of Strings for a History in Java

I am seeking guidance in the respect of optimising code. The code I have written is for a text-based game in which you type in commands into a command bar. One feature I wished to incorporate into my interface was the ability to scroll through a history of one's last 100 commands entered using the up and down arrow keys so that it would be more convenient for the user to play the game.
I have designed a class in which uses a String[] that will store each new entry in the second position (Array[1]) and move all entries back one position while the first position of the array (Array[0]) is just a blank, empty string. The code initialises the array to have 101 values to compensate for the first position being a blank line.
When a user inputs 0 - 100 in that order, it should then give me the reverse of the order (almost like a last in, first out kind of situation, but storing the last 100 values as opposed to removing them once they are accessed), and since 0 - 100 is 101 values, the last value will be overwritten.
Thus, scrolling up through the history, it would give me 100, 99, 98, ..., 2, 1. If I were to select 50 from the list, it would then be 50, 100, 99, ..., 3, 2. The code indeed does this.
The code is listed below:
public class CommandHistory {
private String[] history;
private final int firstIndex = 1;
private static int currentIndex = 0;
/**
* Default constructor, stores last 100 entries of commands plus the blank
* entry at the first index
*/
public CommandHistory() {
history = new String[101];
}
/**
* Constructor with a capacity, stores the last (capacity) entries of
* commands plus the blank entry at the first index
*
* #param capacity
* Capacity of the commands history list
*/
public CommandHistory(int capacity) {
history = new String[capacity + 1];
}
/**
* Returns the size (length) of the history list
*
* #return The size (length) of the history list
*/
private int size() {
return history.length;
}
/**
* Adds a command to the command history log
*
* #param command
* Command to be added to the history log
*/
public void add(String command) {
history[0] = "";
if (!command.equals("")) {
for (int i = firstIndex; i < size();) {
if (history[i] == null) {
history[i] = command;
break;
} else {
for (int j = size() - 1; j > firstIndex; j--) {
history[j] = history[j - 1];
}
history[firstIndex] = command;
break;
}
}
currentIndex = 0;
}
}
/**
* Gets the previous command in the history list
*
* #return The previous command from the history list
*/
public String previous() {
if (currentIndex > 0) {
currentIndex--;
}
return history[currentIndex];
}
/**
* Gets the next command in the history list
*
* #return The next command from the history list
*/
public String next() {
if (currentIndex >= 0 && (history[currentIndex + 1] != null)) {
currentIndex++;
}
return history[currentIndex];
}
/**
* Clears the command history list
*/
public void clear() {
for (int i = firstIndex; i < size(); i++) {
history[i] = null;
}
currentIndex = 0;
}
/**
* Returns the entire command history log
*/
public String toString() {
String history = "";
for (int i = 0; i < size(); i++) {
history += this.history[i];
}
return history;
}
}
In my interface class, once the user types something into the command bar and hits enter, it will get the text currently stored in the bar, uses the add method to add it to the history, parses the command via another class, and then sets the text in the bar to blank.
Pressing the up arrow calls the next method which scrolls up the list, and the down arrow calls the previous method which scrolls down the list.
It seems to work in every way I wish it to, but I was wondering if there was some way to optimise this code or perhaps even code it in a completely different way. I am making this game to keep myself practiced in Java and also to learn new and more advanced things, so I'd love to hear any suggestions on how to do so.
The comments to your question have already pointed out that you are somehow trying to reinvent the wheel by implementing functionality that the standard Java class library already provides to some extent (see LinkedList/Queue and Arraylist). But since you say you want to keep yourself practiced in Java I guess it is perfectly fine if you try to implement your own command history from scratch.
Here are some of my observations/suggestions:
1) It is not necessary and very counter-intuitive to declare a final first index of 1. It would be easy to start with a default index of 0 and add corresponding checks where necessary.
2) Forget about your private size() method - it is just returning the length of the internal array anyway (i.e. the initial capacity+1). Instead consider adding a public size() method that returns the actual number of added commands and internally update the actual size when adding new commands (see e.g. java.util.ArrayList for reference).
3) At the moment every call to add(String command) will set history[0] = "", which is not necessary. If you want the first index to be "", set it in the constructor. This is also a clear sign, that it would perhaps be better to start with an initial index of 0 instead of 1.
4) A minor issue: "if (!command.equals(""))" during your add method is perhaps OK for such a specialized class but it should definitely be commented in the documentation of the method. Personally I would always let the calling class decide if an empty "" command is considered valid or not. Also this method will throw an undocumented NullPointerException, when null is used as an argument. Consider changing this to "if (!"".equals(command))" or throw an IllegalArgumentException if null is added.
5) "if (history[i] == null)" during the add method is completely unnecessary, if you internally keep a pointer to the actual size of the commands - this is actually a special case that will only be true, when the very first command is added to the command history (i.e. when it's actual size == 0).
6) Having two nested for loops in your add method implementation is also unnecessary, if you keep a pointer to the actual size (see example below)
7) I would reconsider if it is necessary to keep a pointer to the current index in the command history. Personally I would avoid storing such a pointer and leave these details to the calling class - i.e. remove the previous and next methods and either provide a forward/backward Iterator and/or a random access to the index of the available commands. Interestingly, when this functionality is removed from your command history class, it actually comes down to either an implementation of a LinkedList or an ArrayList- whichever way you go. So in the end using one of the built in Java collections would actually be the way to go.
8) Last but nor least I would reconsider if it is useful to insert added commands at the beginning of the list - I believe it would be more natural to append them to the end as e.g. ArrayList does. Adding the commands to the end would make the swapping of all current commands during each call to add() unnecessary...
Here are some of the suggested changes to your class (not really tested...)
public class CommandHistory {
private String[] history;
private int size;
private static int currentIndex = 0;
/**
* Default constructor, stores last 100 entries of commands plus the blank
* entry at the first index
*/
public CommandHistory() {
this(100);
}
/**
* Constructor with a capacity, stores the last (capacity) entries of
* commands plus the blank entry at the first index
*
* #param capacity
* Capacity of the commands history list
*/
public CommandHistory(int capacity) {
history = new String[capacity];
}
/**
* Returns the size (length) of the history list
*
* #return The size (length) of the history list
*/
public int size() {
return size;
}
/**
* Adds a command to the command history log
*
* #param command
* Command to be added to the history log
*/
public void add(String command) {
if (!"".equals(command)) {
if (this.size < history.length) {
this.size++;
}
for (int i = size-1; i >0; i--) {
history[i] = history[i-1];
}
history[0] = command;
currentIndex = 0;
}
}
/**
* Gets the previous command in the history list
*
* #return The previous command from the history list
*/
public String previous() {
if (currentIndex >= 0 && currentIndex < size-1) {
currentIndex++;
}
return history[currentIndex];
}
/**
* Gets the next command in the history list
*
* #return The next command from the history list
*/
public String next() {
if (currentIndex > 0 && currentIndex < size) {
currentIndex--;
}
return history[currentIndex];
}
/**
* Clears the command history list
*/
public void clear() {
for (int i = 0; i < size; i++) {
history[i] = null;
}
currentIndex = 0;
}
/**
* Returns the entire command history log
*/
public String toString() {
String history = "";
for (int i = 0; i < size; i++) {
history += this.history[i] + ", ";
}
return history;
}
}
Well, I guess I have invested far too much time for this, but I learned quite a bit myself on the way - so thanks ;-)
Hope some of this is useful for you.

How to avoid infinite loop while creating a scheduler

Intro to problem:
I am given recipes how to craft items. Recipe is in format : {element that is being crafter}: {list of elements, that is needed}. Before I can craft element x, I need to know how to craft elements it's made of. So I want to find in what order do I have to learn recipes.
For valid input, like following everything works:
// Input:
{
"F1: F2 F3 F4", "F5: F6 F4", "F6: F7 F8 F4", "F2: F3 F8 F4", "F8: F4",
"F9: F4", "F7: F4", "F10: F7 F4", "F11: F4", "F4:", "F3: F6"
}
// Output:
[F4, F7, F8, F6, F3, F2, F1, F5, F9, F10, F11]
The problem is, that task is more complex. Time to time I have some recipes missing or thy are invalid. Example of invalid input: { "F1: F2", "F2: F1" }.
Code example:
mp contains recipe name as key and elements as value, labels are unique mp keys and result will contain answer. I'm looking for a way to return empty result if infinite loop is met.
private void getArray(HashMap<String, ArrayList<String>> mp,
ArrayList<String> result, ArrayList<String> labels) {
for (String a : labels) {
if (mp.get(a) != null)
for (String label : mp.get(a))
getArray(mp, result, label);
if (!result.contains(a))
result.add(a);
}
}
private void getArray(HashMap<String, ArrayList<String>> mp,
ArrayList<String> result, String label) {
if (result.contains(label))
return;
if (mp.get(label) == null) {
result.add(label);
return;
}
for (String l : mp.get(label))
getArray(mp, result, l);
if (!result.contains(label))
result.add(label);
}
Edit
Problem solved.
For any Google's that stumble up this, this is what I came up with:
/** <p>
* <b>Topological sort</b> solves a problem of - finding a linear ordering
* of the vertices of <i>V</i> such that for each edge <i>(i, j) ∈ E</i>,
* vertex <i>i</i> is to the left of vertex <i>j</i>. (Skiena 2008, p. 481)
* </p>
*
* <p>
* Method is derived from of <a
* href="http://en.wikipedia.org/wiki/Topological_sort#Algorithms" > Kahn's
* pseudo code</a> and traverses over vertices as they are returned by input
* map. Leaf nodes can have null or empty values. This method assumes, that
* input is valid DAG, so if cyclic dependency is detected, error is thrown.
* tSortFix is a fix to remove self dependencies and add missing leaf nodes.
* </p>
*
* <pre>
* // For input with elements:
* { F1=[F2, F3, F4], F10=[F7, F4], F11=[F4], F2=[F3, F8, F4], F3=[F6],
* F4=null, F5=[F6, F4], F6=[F7, F8, F4], F7=[F4], F8=[F4], F9=[F4]}
*
* // Output based on input map type:
* HashMap: [F4, F11, F8, F9, F7, F10, F6, F5, F3, F2, F1]
* TreeMap: [F4, F11, F7, F8, F9, F10, F6, F3, F5, F2, F1]
* </pre>
*
* #param g
* <a href="http://en.wikipedia.org/wiki/Directed_acyclic_graph"
* > Directed Acyclic Graph</a>, where vertices are stored as
* {#link java.util.HashMap HashMap} elements.
*
* #return Linear ordering of input nodes.
* #throws Exception
* Thrown when cyclic dependency is detected, error message also
* contains elements in cycle.
*
*/
public static <T> ArrayList<T> tSort(java.util.Map<T, ArrayList<T>> g)
throws Exception
/**
* #param L
* Answer.
* #param S
* Not visited leaf vertices.
* #param V
* Visited vertices.
* #param P
* Defined vertices.
* #param n
* Current element.
*/
{
java.util.ArrayList<T> L = new ArrayList<T>(g.size());
java.util.Queue<T> S = new java.util.concurrent.LinkedBlockingDeque<T>();
java.util.HashSet<T> V = new java.util.HashSet<T>(),
P = new java.util.HashSet<T>();
P.addAll(g.keySet());
T n;
// Find leaf nodes.
for (T t : P)
if (g.get(t) == null || g.get(t).isEmpty())
S.add(t);
// Visit all leaf nodes. Build result from vertices, that are visited
// for the first time. Add vertices to not visited leaf vertices S, if
// it contains current element n an all of it's values are visited.
while (!S.isEmpty()) {
if (V.add(n = S.poll()))
L.add(n);
for (T t : g.keySet())
if (g.get(t) != null && !g.get(t).isEmpty() && !V.contains(t)
&& V.containsAll(g.get(t)))
S.add(t);
}
// Return result.
if (L.containsAll(P))
return L;
// Throw exception.
StringBuilder sb = new StringBuilder(
"\nInvalid DAG: a cyclic dependency detected :\n");
for (T t : P)
if (!L.contains(t))
sb.append(t).append(" ");
throw new Exception(sb.append("\n").toString());
}
/**
* Method removes self dependencies and adds missing leaf nodes.
*
* #param g
* <a href="http://en.wikipedia.org/wiki/Directed_acyclic_graph"
* > Directed Acyclic Graph</a>, where vertices are stored as
* {#link java.util.HashMap HashMap} elements.
*/
public static <T> void tSortFix(java.util.Map<T, ArrayList<T>> g) {
java.util.ArrayList<T> tmp;
java.util.HashSet<T> P = new java.util.HashSet<T>();
P.addAll(g.keySet());
for (T t : P)
if (g.get(t) != null || !g.get(t).isEmpty()) {
(tmp = g.get(t)).remove(t);
for (T m : tmp)
if (!P.contains(m))
g.put(m, new ArrayList<T>(0));
}
}
The problem you are solving is known as topological sort. Kahn's algorithm solves the problem while also detecting invalid input (that is, containing cycles).
The quick way to do this is to remember the set of items that you've already seen, and simply throw an exception if you're about to work out the requirements for an item already in that list. This will definitely indicate some kind of circularity which we can probably assume is a bad thing.
A more advanced solution, if loops in the object graph are allowable, would be to not just store the items, but also map them to their solution. Since you're in the process of calculating the solutions, this would perhaps need to be a Future that you pop in the map to indicate that the evaluation may not be complete yet. Then you can add the "solution placeholders" in the map as soon as you visit a given item. Consequently infinite loops work fine (looking at your trivial invalid case):
Visit F1. Put a Future for this in the map. Recurse to work out F2.
Visit F2. Put a Future for this in the map. See that F1 has already been "solved", and record the concrete solution for F2 as simply creating an F1.
This of course represents a loop in the solution's object model, but that's actually a legitimate representation of the input. If you were displaying this graphically, perhaps as a tree that gets expanded one level at a time, this would render appropriately too ("How do I create an F1? You need to make an F2. How do I create that? You need to make an F1", and so on for as many levels as the user expanded the tree).
(Note that while this sounds silly it can actually reflect some valid scenarios; e.g. in Fallout: New Vegas, several crafting recipes convert between different energy ammo types. Thus to make a Microfusion Cell you need three Small Energy Cells. And to make three Small Energy Cells you need a Microfusion Cell. This would create a loop in the graph, but in this case is actually valid input. I'm just pointing this out in case you're assuming that loops are always wrong input.)
If it is possible for a recipe to have alternatives, perhaps somewhere between these two approaches is the best bet. Follow all of the alternative paths, but if you get into an infinite loop, stop following that one and go with the others.

Public class DiscoLight help

If some one can point me in the right direction for this code for my assigment I would really appreciate it.
I have pasted the whole code that I need to complete but I need help with the following method public void changeColour(Circle aCircle) which is meant to allow to change the colour of the circle randomly, if 0 comes the light of the circle should change to red, 1 for green and 2 for purple.
public class DiscoLight
{
/* instance variables */
private Circle light; // simulates a circular disco light in the Shapes window
private Random randomNumberGenerator;
/**
* Default constructor for objects of class DiscoLight
*/
public DiscoLight()
{
super();
this.randomNumberGenerator = new Random();
}
/**
* Returns a randomly generated int between 0 (inclusive)
* and number (exclusive). For example if number is 6,
* the method will return one of 0, 1, 2, 3, 4, or 5.
*/
public int getRandomInt(int number)
{
return this.randomNumberGenerator.nextInt(number);
}
/**
* student to write code and comment here for setLight(Circle) for Q4(i)
*/
public void setLight(Circle aCircle)
{
this.light = aCircle;
}
/**
* student to write code and comment here for getLight() for Q4(i)
*/
public Circle getLight()
{
return this.light;
}
/**
* Sets the argument to have a diameter of 50, an xPos
* of 122, a yPos of 162 and the colour GREEN.
* The method then sets the receiver's instance variable
* light, to the argument aCircle.
*/
public void addLight(Circle aCircle)
{
//Student to write code here, Q4(ii)
this.light = aCircle;
this.light.setDiameter(50);
this.light.setXPos(122);
this.light.setYPos(162);
this.light.setColour(OUColour.GREEN);
}
/**
* Randomly sets the colour of the instance variable
* light to red, green, or purple.
*/
public void changeColour(Circle aCircle)
{
//student to write code here, Q4(iii)
if (getRandomInt() == 0)
{
this.light.setColour(OUColour.RED);
}
if (this.getRandomInt().equals(1))
{
this.light.setColour(OUColour.GREEN);
}
else
if (this.getRandomInt().equals(2))
{
this.light.setColour(OUColour.PURPLE);
}
}
/**
* Grows the diameter of the circle referenced by the
* receiver's instance variable light, to the argument size.
* The diameter is incremented in steps of 2,
* the xPos and yPos are decremented in steps of 1 until the
* diameter reaches the value given by size.
* Between each step there is a random colour change. The message
* delay(anInt) is used to slow down the graphical interface, as required.
*/
public void grow(int size)
{
//student to write code here, Q4(iv)
}
/**
* Shrinks the diameter of the circle referenced by the
* receiver's instance variable light, to the argument size.
* The diameter is decremented in steps of 2,
* the xPos and yPos are incremented in steps of 1 until the
* diameter reaches the value given by size.
* Between each step there is a random colour change. The message
* delay(anInt) is used to slow down the graphical interface, as required.
*/
public void shrink(int size)
{
//student to write code here, Q4(v)
}
/**
* Expands the diameter of the light by the amount given by
* sizeIncrease (changing colour as it grows).
*
* The method then contracts the light until it reaches its
* original size (changing colour as it shrinks).
*/
public void lightCycle(int sizeIncrease)
{
//student to write code here, Q4(vi)
}
/**
* Prompts the user for number of growing and shrinking
* cycles. Then prompts the user for the number of units
* by which to increase the diameter of light.
* Method then performs the requested growing and
* shrinking cycles.
*/
public void runLight()
{
//student to write code here, Q4(vii)
}
/**
* Causes execution to pause by time number of milliseconds
*/
private void delay(int time)
{
try
{
Thread.sleep(time);
}
catch (Exception e)
{
System.out.println(e);
}
}
}
You have forgotten to pass a parameter when calling getRandomInt() in the very first line below //student to write code here. Your compiler should already point this out, though.
The documentation comment above the getRandomInt() method tells you what it expects as parameter, and what you can expect as return value.
Also, if you want equal chances that the lamp is red, green or purple, you should be able to do that with a single invocation of getRandomInt(). Store the value in a variable, and use a switch statement to turn on the correct light:
int randomValue = getRandomInt(/* I am not telling you what to put here */);
switch (randomValue) {
case 0: light.setColour(OUColour.RED); break;
case 1: light.setColour(OUColour.GREEN); break;
case 2: light.setColour(OUColour.PURPLE); break;
}
/**
* Randomly sets the colour of the instance variable
* light to red, green, or purple.
*/
public void changeColour(Circle aCircle)
{
int i = getRandomInt(3);
if (i == 0)
{
this.light.setColour(OUColour.RED);
}
else if (i == 1)
{
this.light.setColour(OUColour.GREEN);
}
else
{
this.light.setColour(OUColour.PURPLE);
}
}
the method getRandomInt returns an int, so you can't use equals to compare. use:
if (getRandomInt(3) == 1) {
...
}
and you just need to call it once. store the random integer in a variable and compare its value with the ones you want.
you're calling getRandomInt several times, with each time a new (random) value returned.
you should call it once at the begin of the method, and then check if it is 0,1 or 2.
Regards
Guillaume

Categories