I'm working on the standard 8 puzzle solver, and have successfully gotten it to work with BFS. Depth first, on the other hand, infinitely loops. Here's my code for the DFS algoritm:
public static void depthFirstSolver(PuzzleNode initialNode)
{
Stack<PuzzleNode> puzzleStack = new Stack<PuzzleNode>();
puzzleStack.push(initialNode);
HashSet<PuzzleNode> visitedPuzzles = new HashSet<PuzzleNode>();
int[][] goalState = initialNode.getGoalState();
for(PuzzleNode pn : initialNode.childrenPuzzles)
{
pn.generateChildren();
puzzleStack.push(pn);
}
while(!puzzleStack.isEmpty())
{
PuzzleNode temp = puzzleStack.pop();
temp.generateChildren();
LinkedList<PuzzleNode> childrenPuzzles = temp.childrenPuzzles;
if(Arrays.deepEquals(temp.getPuzzleState(), goalState))
{
System.out.println("CURRENT STATE: ");
temp.printPuzzleState();
temp.findCompletePathFromRoot();
break;
}
else
{
if(!visitedPuzzles.contains(temp))
{
for(PuzzleNode pn : childrenPuzzles)
{
pn.generateChildren();
puzzleStack.push(pn);
}
temp.setPuzzleNodeVisited();
temp.printPuzzleState();
}
}
}
}
Here is the generateChildren method:
public void generateChildren()
{
for(int i = 0; i < 4; i++)
{
PuzzleNode temp = new PuzzleNode(puzzleState, this);
if(temp.moveBlank(i) == true)
{
System.out.println("I:" + i); //diag
childrenPuzzles.add(temp);
temp.printPuzzleState(); //diag
}
}
}
Also, here is moveBlank:
public boolean moveBlank(int whichDirectionToMove)
{
//0 = left, 1 = right, 2 = up, 3 = down
boolean[] placesToMove = getMovableBlankPositions();
if(placesToMove[whichDirectionToMove] == false)
return false;
//DIAG
System.out.println("************************************");
//DIAG
switch(whichDirectionToMove)
{
case 0: //left
{
int temp = puzzleState[blankRow][blankCol - 1];
puzzleState[blankRow][blankCol - 1] = 0;
puzzleState[blankRow][blankCol] = temp;
blankCol--;
movementType = "move blank left";
// DIAG
System.out.println("moved blank left");
// DIAG
break;
}
case 1: //right
{
int temp = puzzleState[blankRow][blankCol + 1];
puzzleState[blankRow][blankCol + 1] = 0;
puzzleState[blankRow][blankCol] = temp;
blankCol++;
movementType = "move blank right";
// DIAG
System.out.println("moved blank right");
// DIAG
break;
}
case 2: //up
{
int temp = puzzleState[blankRow - 1][blankCol];
puzzleState[blankRow - 1][blankCol] = 0;
puzzleState[blankRow][blankCol] = temp;
blankRow--;
movementType = "move blank up";
// DIAG
System.out.println("moved blank up");
// DIAG
break;
}
case 3: //down
{
int temp = puzzleState[blankRow + 1][blankCol];
puzzleState[blankRow + 1][blankCol] = 0;
puzzleState[blankRow][blankCol] = temp;
blankRow++;
movementType = "move blank down";
// DIAG
System.out.println("moved blank down");
// DIAG
break;
}
}
return true;
}
In essence, move blank is given a value 0-3, where: 0 = left, 1 = right, 2 = up, 3 = down. The PuzzleNode class contains a linkedlist of potential moves. This list is called childrenPuzzles, and is updated when the generateChildren() method is called. getMovableBlankPositions() returns a 4 index bool array, whose indicies (and t/f value), determine if the space in these directions can be used. BFS works great, it's DFS that infinitely loops. Any suggestions?
Here the main problem is that u are using same puzzleState array to make the child nodes which is wrong way to do it because the same reference is modified everytime you create a child and all child will have the same puzzleState at the end.
Note:- To get around it u must use new puzzleState array to create children.
Related
The program basically prompts the user to pick one of the displayed moves and move the horse pawn in the chess board. Ιn this way we try to see how many times the horse can move to the chessboard without being out of bounds or even in the same position.
The problem is that I haven't figured out a way to place a number (starting from 1) for the positions where the horse has been to. More specifically I want it to print H in the current position of the horse and 1 to ... on the past positions.
import java.util.Scanner;
public class Ex7_22 {
private static Scanner scanner = new Scanner(System.in);
private static String[][] board = new String[8][8];
private static int[] horizontal = new int[8];
private static int[] vertical = new int[8];
private static boolean[][] boardPositions = new boolean[8][8];
private static int currentRow = 3;
private static int currentColumn = 4;
public static void main(String[] args){
fillArrays();
boolean outOfBoundsV;
boolean outOfBoundsH;
boolean positionAvailability = false;
int VerticalMove,HorizontalMove;
fillBoard();
board[3][4] = "H";
boardPositions[3][4] = true;
displayBoard();
int pickMove;
for(int i=1;i<=64;i++){
displayBoardPositions();
displayPossibleMoves();
do {
System.out.println("\nPick one of the displayed moves to do (0-7): ");
pickMove = scanner.nextInt();
VerticalMove = moveHorse_Vertical(pickMove);
HorizontalMove = moveHorse_Horizontal(pickMove);
outOfBoundsV = checkForOutOfBounds(VerticalMove);
outOfBoundsH = checkForOutOfBounds(HorizontalMove);
if ((outOfBoundsV)||(outOfBoundsH)){
reverse(pickMove);
}
if((!outOfBoundsV)&&(!outOfBoundsH)){
positionAvailability = checkForPositionAvailability(VerticalMove,HorizontalMove);
if((!positionAvailability)){
reverse(pickMove);
}
}
}while (((outOfBoundsV)||(outOfBoundsH))||(!positionAvailability));
board[VerticalMove][HorizontalMove] = "H";
//placeNumber(VerticalMove,HorizontalMove,pickMove);
boardPositions[VerticalMove][HorizontalMove] = true;
displayBoard();
}
}
/* private static void placeNumber(int VerticalMove, int HorizontalMove, int pickMove) {
//have to place number in every position the horse has been to. Haven't managed to get it working.
reverse(pickMove);
int i=0;
i++;
String iStr = String.valueOf(i);
board[VerticalMove][HorizontalMove] = iStr;
currentRow += vertical[pickMove];
currentColumn += horizontal[pickMove];
} */
private static void reverse(int move){
currentRow -= vertical[move];
currentColumn -= horizontal[move];
}
private static void fillBoard(){
for(int i=0;i<board.length;i++){
for(int j=0;j<board[i].length;j++){
board[i][j] = "0";
}
}
}
private static boolean checkForPositionAvailability(int vertical, int
horizontal) {
if(!boardPositions[vertical][horizontal]){
return true;
}
else{
System.out.println("You've already been in this position.");
return false;
}
}
private static boolean checkForOutOfBounds(int position) {
if((position<0)||(position>=8)){
System.out.print("Position out of bounds\nPlease choose another move\n");
return true;
}
else return false;
}
private static int moveHorse_Vertical(int move) {
currentRow += vertical[move];
return currentRow;
}
private static int moveHorse_Horizontal(int move){
currentColumn += horizontal[move];
return currentColumn;
}
private static void fillArrays() {
//fill horizontal array
horizontal[0] = 2;
horizontal[1] = 1;
horizontal[2] = -1;
horizontal[3] = -2;
horizontal[4] = -2;
horizontal[5] = -1;
horizontal[6] = 1;
horizontal[7] = 2;
//fill vertical array
vertical[0] = -1;
vertical[1] = -2;
vertical[2] = -2;
vertical[3] = -1;
vertical[4] = 1;
vertical[5] = 2;
vertical[6] = 2;
vertical[7] = 1;
}
private static void displayBoard(){
System.out.print("\n");
System.out.println(" 0 1 2 3 4 5 6 7");
System.out.println(" ----------------------------- ");
for(int i=0;i<board.length;i++){
System.out.print(i + "|\t");
for(int j=0;j<board[i].length;j++){
System.out.print(" "+board[i][j] + "\t");
}
System.out.println();
}
}
private static void displayBoardPositions(){
System.out.print("\n");
System.out.println(" 0 1 2 3 4 5 6 7");
System.out.println(" ----------------------------- ");
for(int i=0;i<boardPositions.length;i++){
System.out.print(i + "|\t");
for(int j=0;j<boardPositions[i].length;j++){
System.out.print(" "+boardPositions[i][j] + "\t");
}
System.out.println();
}
}
private static void displayPossibleMoves(){
System.out.println("\n0 -> 1 move up // 2 moves right.\n" +
"1 -> 2 moves up // 1 move right.\n" +
"2 -> 2 moves up // 1 move left.\n" +
"3 -> 1 move up // 2 moves left.\n" +
"4 -> 1 move down // 2 moves left.\n" +
"5 -> 1 move left // 2 moves down.\n" +
"6 -> 1 move right // 2 moves down.\n" +
"7 -> 1 move down // 2 moves right.");
}
}
Hey i don't think you need to change much. You just need to add two integers that keep track of your previous position. I tried to keep the modifications of your code to a minimum:
int previousRow = 3;
int previousColumn = 4;
and update them after you set the current position to "H":
Here is a modified version of your public static main(String[] args):
public static void main(String[] args){
fillArrays();
boolean outOfBoundsV;
boolean outOfBoundsH;
boolean positionAvailability = false;
int VerticalMove,HorizontalMove;
fillBoard();
board[3][4] = "H";
boardPositions[3][4] = true;
// add the two integers that keep track of you previous position:
int previousRow = 3;
int previousColumn = 4;
displayBoard();
int pickMove;
for(int i=1;i<=64;i++){
displayBoardPositions();
displayPossibleMoves();
do {
System.out.println("\nPick one of the displayed moves to do (0-7): ");
pickMove = scanner.nextInt();
VerticalMove = moveHorse_Vertical(pickMove);
HorizontalMove = moveHorse_Horizontal(pickMove);
outOfBoundsV = checkForOutOfBounds(VerticalMove);
outOfBoundsH = checkForOutOfBounds(HorizontalMove);
if ((outOfBoundsV)||(outOfBoundsH)){
reverse(pickMove);
}
if((!outOfBoundsV)&&(!outOfBoundsH)){
positionAvailability = checkForPositionAvailability(VerticalMove,HorizontalMove);
if((!positionAvailability)){
reverse(pickMove);
}
}
} while ((outOfBoundsV)||(outOfBoundsH)||(!positionAvailability));
// set the previous position to your current step of i:
board[previousRow][previousColumn] = String.valueOf(i);
board[VerticalMove][HorizontalMove] = "H";
//update your previous position, with your current position
previousColumn = currentColumn;
previousRow = currentRow;
boardPositions[VerticalMove][HorizontalMove] = true;
displayBoard();
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I need to calculate the minimum number of jumps to reach the end of an Array with dice throw Array Value may be negative/positive value:
when positive----> Move Forward
when negative ------> go back
The Array may also contain R value, which means that the player have to throw the dice again
The start position is marked on our Array with S and End position with E The Start Position is not always the first element of the Array and End position is not always at the end, it can even be before S
Example: Array = {4, S, -2,1, R, 4,3,4,3,-5,2,-4, E}
the player start on S position the fastest way to reach E:
Throwing the dice to have 3 and reach the R case (first move)
throwing the dice again and having 6 to reach the 2 Case (second movement)
Jumping 2 cases to reach E (third move)
so the best solution for this example is: 3 moves
Lets give you a hint: the key thing to learn here: sometimes you have to transform your input data in order to find a good way to solve your problem.
In your case; consider turning your array into a graph:
Each array index is a node within that graph
The value of each array position tells you something about edges to other nodes. For example, if a(0) is R; then a(0) would be connected to a(1), a(2) .. a(6) - because you can reach the next 6 elements.
For starters; I would suggest to do that manually; just draw the graph for example array.
So, the steps to solve your problem:
Transform your array into a graph
Search the net for algorithms to find minimum length paths in graphs
Print out that path; resulting in the minimal list from S to E
Implementation is left as exercise to the reader.
I wrote this working solution i share it for anyone interested , but when it comes to deal with big Array (3000 for example) it throws a java heap space error as the code will consume huge amount of memory , any help or advice will be appreciated
public class Solution {
static int startPosition;
public static int compute(BufferedReader br) throws IOException {
final int totalNodeCount = getTotalNodeNumber(br);
final String caseArray[] = new String[totalNodeCount];
bufferToArray(br, caseArray);
startPosition = getStartPosition(caseArray);
final boolean visited[] = new boolean[caseArray.length];
int minimumNumberOfMove = 0;
final List<Integer> reachableList = new ArrayList<Integer>();
for (int i = 1; i <= 6; i++)
{
visitedInitilise(visited);
if (((startPosition + i) < totalNodeCount) && ((startPosition + i) > 0))
getMinimumNumberOfMoves(caseArray, visited, startPosition + i, 0, reachableList);
}
// Retriving Minimum number of move from all reachble route
if (reachableList.isEmpty())
minimumNumberOfMove = Constants.IMPOSSIBLE;
else
{
minimumNumberOfMove = reachableList.get(0);
for (int i = 0; i < reachableList.size(); i++)
if (reachableList.get(i) < minimumNumberOfMove)
minimumNumberOfMove = reachableList.get(i);
}
return minimumNumberOfMove;
}
static int getStartPosition(String[] plateau){
int startIndex = 0;
for (int i = 0; i <= (plateau.length - 1); i++)
if (plateau[i].equals("S"))
{
startIndex = i;
break;
}
return startIndex;
}
static void bufferToArray(BufferedReader br, String[] plateau) {
String line;
int i = 0;
try
{
while ((line = br.readLine()) != null)
{
plateau[i] = line;
i++;
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
static int getTotalNodeNumber(BufferedReader br) {
int i = 0;
try
{
i = Integer.parseInt(br.readLine());
} catch (NumberFormatException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
return i;
}
static List<Integer> getMinimumNumberOfMoves(String[] plateau, boolean[] visited, final int currentIndex,
int currentNumberOfMoves, List<Integer> list) {
Boolean endIsReached = false;
Boolean impossible = false;
visited[startPosition] = true;
// Checking if the current index index is negativ
if (currentIndex < 0)
impossible = true;
while ((endIsReached == false) && (impossible == false) && (visited[currentIndex] == false)
&& (currentIndex < plateau.length))
{
try
{
switch (plateau[currentIndex]) {
case "E": {
// if end is reached , pushing number of move into our list
endIsReached = true;
list.add(currentNumberOfMoves + 1);
break;
}
case "R": {
// Marking node as visited
visited[currentIndex] = true;
for (int i = 1; i <= 6; i++)
{
// Marking all case after R case as non visited
for (int j = currentIndex + 1; j < visited.length; j++)
visited[j] = false;
// Calculating number of move after R case
if (((currentIndex + i) < plateau.length) && (currentIndex > 0))
getMinimumNumberOfMoves(plateau, visited, currentIndex + i, currentNumberOfMoves + 1, list);
}
break;
}
default: {
// Cheking if node was already visited
if (visited[currentIndex] == true)
{
// Marking all node as non visited
visitedInitilise(visited);
impossible = true;
break;
}
else
{
// when the node was not visited before , catch the jump
// value
int jumpValue = Integer.parseInt(plateau[currentIndex]);
// cheking that the next node is not bigger than node
// number and not negativ
if (((currentIndex + jumpValue) > plateau.length) || (currentIndex < 0))
{
impossible = true;
break;
}
else
{
// Marking node as visited
visited[currentIndex] = true;
// calculating minimum number of move starting from
// this node
getMinimumNumberOfMoves(plateau, visited, currentIndex + jumpValue,
currentNumberOfMoves + 1, list);
break;
}
}
}
}
}
catch (NumberFormatException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
if (impossible == true)
currentNumberOfMoves = 0;
return list;
}
static void visitedInitilise(boolean visited[]) {
for (int i = 0; i <= (visited.length - 1); i++)
visited[i] = false;
}
public static void main(String args[]){
String testCaseID = "15"; // Write a test file number from 1 to 15, or
// ALL
TestCases.test(testCaseID);
}
}
I am making a robot maze where the robot reaches a target automatically without crashing into walls. I want the robot to do the maze once, learn the correct route and then the second time be able to get there straight away without going to any deadends. I thought I could do this by making three arraylists.
One for all the squares the robot visits.
Two for all the squares that lead to a deadend.
Three for all the directions the robot goes.
If the squares that lead to a dead end are found in the first arraylist then i can delete the same indexes in the third arraylist. That way, the second time, i can just iterate the third Arraylist.
My full code is below:
import java.util.ArrayList;
import java.util.*;
import java.util.Iterator;
import java.util.stream.IntStream;
public class Explorer {
private int pollRun = 0; // Incremented after each pass.
private RobotData robotData; // Data store for junctions.
private ArrayList<Integer> nonWallDirections;
private ArrayList<Integer> passageDirections;
private ArrayList<Integer> beenbeforeDirections;
private Random random = new Random();
int [] directions = {IRobot.AHEAD, IRobot.LEFT, IRobot.RIGHT, IRobot.BEHIND};
private ArrayList<Square> correctSquares;
private ArrayList<Square> wrongSquares;
private ArrayList<Integer> correctDirections;
public void controlRobot (IRobot robot) {
// On the first move of the first run of a new maze.
if ((robot.getRuns() == 0) && (pollRun ==0))
robotData = new RobotData();
pollRun++; /* Increment poll run so that the data is not reset
each time the robot moves. */
int exits = nonwallExits(robot);
int direction;
if ((robot.getRuns() != 0))
direction = grandfinale(robot);
nonWallDirections = new ArrayList<Integer>();
passageDirections = new ArrayList<Integer>();
beenbeforeDirections = new ArrayList<Integer>();
correctSquares = new ArrayList<Square>();
correctDirections = new ArrayList<Integer>();
// Adding each direction to the appropriate state ArrayList.
for(int item : directions) {
if(robot.look(item) != IRobot.WALL) {
nonWallDirections.add(item);
}
}
for(int item : directions) {
if(robot.look(item) == IRobot.PASSAGE) {
passageDirections.add(item);
}
}
for(int item : directions) {
if(robot.look(item) == IRobot.BEENBEFORE) {
beenbeforeDirections.add(item);
}
}
// Calling the appropriate method depending on the number of exits.
if (exits < 2) {
direction = deadEnd(robot);
} else if (exits == 2) {
direction = corridor(robot);
} else {
direction = junction(robot);
robotData.addJunction(robot);
robotData.printJunction(robot);
}
robot.face(direction);
addcorrectSquares(robot);
correctDirections.add(direction);
}
/* The specification advised to have to seperate controls: Explorer and Backtrack
and a variable explorerMode to switch between them.
Instead, whenever needed I shall call this backtrack method.
If at a junction, the robot will head back the junction as to when it first approached it.
When at a deadend or corridor, it will follow the beenbefore squares until it
reaches an unexplored path. */
public int backtrack (IRobot robot) {
if (nonwallExits(robot) > 2) {
addwrongSquares(robot);
return robotData.reverseHeading(robot);
} else {
do {
addwrongSquares(robot);
return nonWallDirections.get(0);
} while (nonwallExits(robot) == 1);
}
}
// Deadend method makes the robot follow the only nonwall exit.
public int deadEnd (IRobot robot) {
return backtrack(robot);
}
/* Corridor method will make the robot follow the one and only passage.
The exception is at the start. Sometimes, the robot will start with
two passages available to it in which case it will choose one randomly.
If there is no passage, it will follow the beenbefore squares
until it reaches an unexplored path.*/
public int corridor (IRobot robot) {
if (passageExits(robot) == 1) {
return passageDirections.get(0);
} else if (passageExits(robot) == 2) {
int randomPassage = random.nextInt(passageDirections.size());
return passageDirections.get(randomPassage);
} else {
return backtrack(robot);
}
}
/* Junction method states if there is more than one passage, it will randomly select one.
This applies to crossroads as well as essentially they are the same.
If there is no passage, it will follow the beenbefore squares until it reaches an unexplored
path. */
public int junction(IRobot robot) {
if (passageExits(robot) == 1) {
return passageDirections.get(0);
} else if (passageExits(robot) > 1) {
int randomPassage = random.nextInt(passageDirections.size());
return passageDirections.get(randomPassage);
} else {
return backtrack(robot);
}
}
// Calculates number of exits.
private int nonwallExits (IRobot robot) {
int nonwallExits = 0;
for(int item : directions) {
if(robot.look(item) != IRobot.WALL) {
nonwallExits++;
}
}
return nonwallExits;
}
// Calculates number of passages.
private int passageExits (IRobot robot) {
int passageExits = 0;
for(int item : directions) {
if(robot.look(item) == IRobot.PASSAGE) {
passageExits++;
}
}
return passageExits;
}
// Calculates number of beenbefores.
private int beenbeforeExits (IRobot robot) {
int beenbeforeExits = 0;
for(int item : directions) {
if(robot.look(item) == IRobot.PASSAGE) {
beenbeforeExits++;
}
}
return beenbeforeExits;
}
// Resets Junction Counter in RobotData class.
public int reset() {
return robotData.resetJunctionCounter();
}
public void addcorrectSquares(IRobot robot) {
Square newSquare = new Square(robot.getLocation().x, robot.getLocation().y);
correctSquares.add(newSquare);
}
public void addwrongSquares(IRobot robot) {
Square badSquare = new Square(robot.getLocation().x, robot.getLocation().y);
wrongSquares.add(badSquare);
}
public int grandfinale (IRobot robot) {
IntStream.range(0, correctSquares.size())
.map(index -> correctSquares.size() - index - 1)
.filter(index -> (((wrongSquares.x).contains(correctSquares.x)) && ((wrongSquares.y).contains(correctSquares.y))).get(index))
.forEach(index -> correctDirections.remove(index));
Iterator<Integer> routeIterator = correctDirections.iterator();
while (routeIterator.hasNext()) {
break;
}
return (routeIterator.next());
}
}
class RobotData {
/* It was advised in the specification to include the variable:
private static int maxJunctions = 10000;
However, as I am not using arrays, but ArrayLists, I do not
need this. */
private static int junctionCounter = 0;
private ArrayList<Junction> junctionList = new ArrayList<Junction>();
// Resets the Junction counter.
public int resetJunctionCounter() {
return junctionCounter = 0;
}
// Adds the current junction to the list of arrays.
public void addJunction(IRobot robot) {
Junction newJunction = new Junction(robot.getLocation().x, robot.getLocation().y, robot.getHeading());
junctionList.add(newJunction);
junctionCounter++;
}
// Gets the junction counter for Junction info method in Junction class.
public int getJunctionCounter (IRobot robot) {
return junctionCounter;
}
// Prints Junction info.
public void printJunction(IRobot robot) {
String course = "";
switch (robot.getHeading()) {
case IRobot.NORTH:
course = "NORTH";
break;
case IRobot.EAST:
course = "EAST";
break;
case IRobot.SOUTH:
course = "SOUTH";
break;
case IRobot.WEST:
course = "WEST";
break;
}
System.out.println("Junction " + junctionCounter + " (x=" + robot.getLocation().x + ", y=" + robot.getLocation().y +") heading " + course);
}
/* Iterates through the junction arrayList to find the
heading of the robot when it first approached the junction.
It does this by finding the first junction in the ArrayList
that has the same x and y coordinates as the robot.*/
public int searchJunction(IRobot robot) {
Junction currentJunction = null;
Iterator<Junction> junctionIterator = junctionList.iterator();
while (junctionIterator.hasNext()) {
currentJunction = junctionIterator.next();
if ((((currentJunction.x)==(robot.getLocation().x))) && ((currentJunction.y)==(robot.getLocation().y)))
break;
}
return currentJunction.arrived;
}
// Returns the reverse of the heading the robot had when first approaching the junction.
public int reverseHeading(IRobot robot) {
int firstHeading = searchJunction(robot);
int reverseHeading = 1; // Random integer to Iniitalise variable.
switch (firstHeading) {
case IRobot.NORTH:
if (robot.getHeading() == IRobot.NORTH)
reverseHeading = IRobot.BEHIND;
else if (robot.getHeading() == IRobot.EAST)
reverseHeading = IRobot.RIGHT;
else if (robot.getHeading() == IRobot.SOUTH)
reverseHeading = IRobot.AHEAD;
else
reverseHeading = IRobot.LEFT;
break;
case IRobot.EAST:
if (robot.getHeading() == IRobot.NORTH)
reverseHeading = IRobot.LEFT;
else if (robot.getHeading() == IRobot.EAST)
reverseHeading = IRobot.BEHIND;
else if (robot.getHeading() == IRobot.SOUTH)
reverseHeading = IRobot.RIGHT;
else
reverseHeading = IRobot.AHEAD;
break;
case IRobot.SOUTH:
if (robot.getHeading() == IRobot.NORTH)
reverseHeading = IRobot.AHEAD;
else if (robot.getHeading() == IRobot.EAST)
reverseHeading = IRobot.LEFT;
else if (robot.getHeading() == IRobot.SOUTH)
reverseHeading = IRobot.BEHIND;
else
reverseHeading = IRobot.RIGHT;
break;
case IRobot.WEST:
if (robot.getHeading() == IRobot.NORTH)
reverseHeading = IRobot.RIGHT;
else if (robot.getHeading() == IRobot.EAST)
reverseHeading = IRobot.AHEAD;
else if (robot.getHeading() == IRobot.SOUTH)
reverseHeading = IRobot.LEFT;
else
reverseHeading = IRobot.BEHIND;
break;
}
return reverseHeading;
}
}
class Junction {
int x;
int y;
int arrived;
public Junction(int xcoord, int ycoord, int course) {
x = xcoord;
y = ycoord;
arrived = course;
}
}
class Square {
int x;
int y;
public Square(int cordx, int cordy){
x = cordx;
y = cordy;
}
}
IntStream.range(0, al1.length)
.filter(index -> al2.contains(al1.get(index)))
.forEach(index -> al3.remove(index));
Slightly more complex than this if removing elements from al3 shifts them left but in that case just reverse the stream before the .filter- then it will delete from the end. The easiest way to do that is:
.map(index -> al1.length - index - 1)
Without Streams the equivalent would be
for (int i = 0; i < al1.length; i++) {
if (al2.contains(al1.get(i))) {
al3.remove(i);
}
}
Similarly, if you need to delete from the right then the for loop would need to count down rather than up.
Without further details on arraylist structure it's hard to give any more hints.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I'm trying to code a battleship game and im getting a weird error when i run it: Exception in thread "main" java.lang.NullPointerException
at Caculations.findShip(Caculations.java:29)
at Board.main(Board.java:60)
Please help im stuck and i dont know how to continue! Here is my code: (Note, its in 2 class files in my eclipse work enviorment)
public class Board {
public static void main(String[] args) {
boolean continuePlay = true;
int[][] board = new int[10][10]; // creating 2d array 'board'
char[][] boardGraphical = new char[10][10]; // creating 2d array 'board
// this time the visual
for (int x = 0; x < 10; x++) { // for within for //initializing elements
// in both boards using double for
// method
for (int y = 0; y < 10; y++) {
board[x][y] = 0;
boardGraphical[x][y] = 'o';
System.out.println("Board element " + x + " " + y // printing
// initialized
// elements
// here
+ " initialized");
}
}
/*
* 1) Make user ships 1 and computer ships 2 (all numbers other than 0 =
* true)
*
* 2) Make it where if the computer gets a hit on a '1' than it sets
* that value to like a 3 or something so it knows when the ship is
* sunk. So in a if it does if([x][y] && [x][y])
* System.out.println("You sunk my ship!");
*
* 3) REMEMBER YOU CAN DO MULTIPLE IFS INSIDE IFS FOR MULTIPLE
* CONDITIONS. 4) declare ships here!
*
* 5) PUT STUFF IN A WHILE LOOP SO COMP CAN KEEP GOING
*/
board[3][3] = 1; // declaring a battleship. Very important.
board[3][4] = 1;
board[3][5] = 1;
boardGraphical[3][3] = 's';
boardGraphical[3][4] = 's';
boardGraphical[3][5] = 's';
while (continuePlay == true) { // while loop so that computer keeps
// guessing
// WITHIN THIS LOOP KEEP REPRINTING THE BOARD
double computerChoiceXd = Math.floor(Math.random() * 10); // using
// Math.random
// functions
// for
// computers
// first
// guess
// to be
// a
// random
// num
double computerChoiceYd = Math.floor(Math.random() * 10);
int computerChoiceX = (int) computerChoiceXd;
int computerChoiceY = (int) computerChoiceYd;
if (board[computerChoiceX][computerChoiceY] == 1) { // checking if
// math.random
// landed on a
// ship point
System.out.println("Computer got a hit at " + computerChoiceX
+ " " + computerChoiceY);
board[computerChoiceX][computerChoiceY] = 2; // setting the
// point as 2 or
// 'hit'
boardGraphical[computerChoiceX][computerChoiceY] = 'H';
for (int row = 0; row < 10; row++) { // printing out graphical
// board using the same
// method as when
// intializing
for (int col = 0; col < 10; col++) {
System.out.print(boardGraphical[row][col]);
}
System.out.println(" "); // spacer for printing
}
Caculations test = new Caculations(computerChoiceX, // Creating
// a new
// object of
// calculation
computerChoiceY, board);
test.findShip();
// break;
if (board[3][3] == 2) { // checking to see if ship is sunk using
// a triple if statement
if (board[3][4] == 2) {
if (board[3][5] == 2) {
System.out.println("Battleship sunk!");
continuePlay = false; // if so than it breaks out of
// loop to end the game
break;
}
}
}
} else if (board[computerChoiceX][computerChoiceY] == 0) { // otherwise
// if
// the
// area
// is a
// 0 or
// 'unmarked'
System.out.println("Computer missed at " + computerChoiceX
+ " " + computerChoiceY);
boardGraphical[computerChoiceX][computerChoiceY] = 'x'; // mark
// area
// as a
// miss
for (int row = 0; row < 10; row++) { // print out board
for (int col = 0; col < 10; col++) {
System.out.print(boardGraphical[row][col]);
}
System.out.println(" ");
}
}
}
}
}
public class Caculations {
int xValue;
int yValue;
int[][] myArray;
int[][] storage = new int[10][10];
boolean xAxisChangeP;
boolean yAxisChangeP;
boolean xAxisChangeN;
boolean yAxisChangeN;
boolean notSunk;
Caculations(int x, int y, int[][] myArray) {
xValue = x;
yValue = y;
xAxisChangeP = true;
yAxisChangeP = true;
xAxisChangeN = true;
yAxisChangeN = true;
notSunk = true;
}
void findShip() {
while (notSunk == true) {
// 1
while (xAxisChangeP == true) {
if (myArray[xValue + 1][yValue] == 1) {
myArray[xValue + 1][yValue] = 2;
if (myArray[3][3] == 2) {
if (myArray[3][4] == 2) {
if (myArray[3][5] == 2) {
System.out.println("Battleship sunk!");
notSunk = false;
}
}
}
continue;
}
else {
xAxisChangeP = false;
}
}
while (xAxisChangeN == true) {
if (myArray[xValue - 1][yValue] == 1) {
myArray[xValue - 1][yValue] = 2;
if (myArray[3][3] == 2) {
if (myArray[3][4] == 2) {
if (myArray[3][5] == 2) {
System.out.println("Battleship sunk!");
notSunk = false;
}
}
}
continue;
}
else {
xAxisChangeN = false;
}
}
// 1
while (yAxisChangeP == true) {
if (myArray[xValue][yValue + 1] == 1) {
myArray[xValue][yValue + 1] = 2;
if (myArray[3][3] == 2) {
if (myArray[3][4] == 2) {
if (myArray[3][5] == 2) {
System.out.println("Battleship sunk!");
notSunk = false;
}
}
}
continue;
}
else {
yAxisChangeP = false;
}
}
while (yAxisChangeN == true) {
if (myArray[xValue][yValue - 1] == 1) {
myArray[xValue][yValue - 1] = 2;
if (myArray[3][3] == 2) {
if (myArray[3][4] == 2) {
if (myArray[3][5] == 2) {
System.out.println("Battleship sunk!");
notSunk = false;
}
}
}
continue;
}
else {
yAxisChangeN = false;
}
}
}
}
}
Have you initialized myarray? Best is debug your code to see, which statement throws the exception. In eclipse you can add NullPointerExeption as your breakpoint and debug.
You use myArray, but you never initialize it.
public class Caculations {
int xValue;
int yValue;
int[][] myArray; // array declared but never initialized
// ....
void findShip() {
while (notSunk == true) {
// 1
while (xAxisChangeP == true) {
if (myArray[xValue + 1][yValue] == 1) // then you use it here
Solution: initialize variables before using.
More importantly, you need to learn the general concepts of how to debug a NPE (NullPointerException). You should critically read your exception's stacktrace to find the line of code at fault, the line that throws the exception, and then inspect that line carefully, find out which variable is null, and then trace back into your code to see why. You will run into these again and again, trust me.
In your constructor for Calculations, you never initialized myArray:
Caculations(int x, int y, int[][] myArray) {
xValue = x;
yValue = y;
xAxisChangeP = true;
yAxisChangeP = true;
xAxisChangeN = true;
yAxisChangeN = true;
notSunk = true;
this.myArray = myArray; //Add this line
}
This is a direct answer to your problem, but all in all, you should do some research regarding the meaning behind the exception that was thrown so you understand what it means.
Why this problem happened
In Java, all objects and primitives, if not initialized manually, are given a default value.
For default values of primitives, check this: Primitive Data Types
In case of non-primitive types - such as Object, String, Thread, etc, as well as any user-defined class (i.e. Calculations) and also arrays (i.e. myArray) - the default value is null.
With that in mind, inside your constructor, as exemplified above, you have not initialized myArray, which means that when this variable was accessed for the first time, the value returned was null.
So, what's the problem with null?
Well, by itself, it does no harm. It's there. It doesn't bother you. Until you decide to use a variable that doesn't have an object assigned to it, but somehow you forget that and treat it as if it held something like a String or an array.
That's when Java will tell you: "Hey! There's no object here. I can't work like this. Let's throw an exception!".
OK, I don't know how to word this question, but maybe my code will spell out the problem:
public class ControllerTest
{
public static void main(String [] args)
{
GamePadController rockbandDrum = new GamePadController();
DrumMachine drum = new DrumMachine();
while(true)
{
try{
rockbandDrum.poll();
if(rockbandDrum.isButtonPressed(1)) //BLUE PAD HhiHat)
{
drum.playSound("hiHat.wav");
Thread.sleep(50);
}
if(rockbandDrum.isButtonPressed(2)) //GREEN PAD (Crash)
{
//Todo: Change to Crash
drum.playSound("hiHat.wav");
Thread.sleep(50);
}
//Etc....
}
}
}
public class DrumMachine
{
InputStream soundPlayer = null;
AudioStream audio = null;
static boolean running = true;
public void playSound(String soundFile)
{
//Tak a sound file as a paramater and then
//play that sound file
try{
soundPlayer = new FileInputStream(soundFile);
audio = new AudioStream(soundPlayer);
}
catch(FileNotFoundException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
AudioPlayer.player.start(audio);
}
//Etc... Methods for multiple audio clip playing
}
Now the problem is, if I lower the delay in the
Thread.sleep(50)
then the sound plays multiple times a second, but if I keep at this level or any higher, I could miss sounds being played...
It's an odd problem, where if the delay is too low, the sound loops. But if it's too high it misses playing sounds. Is this just a problem where I would need to tweak the settings, or is there any other way to poll the controller without looping sound?
Edit: If I need to post the code for polling the controller I will...
import java.io.*;
import net.java.games.input.*;
import net.java.games.input.Component.POV;
public class GamePadController
{
public static final int NUM_BUTTONS = 13;
// public stick and hat compass positions
public static final int NUM_COMPASS_DIRS = 9;
public static final int NW = 0;
public static final int NORTH = 1;
public static final int NE = 2;
public static final int WEST = 3;
public static final int NONE = 4; // default value
public static final int EAST = 5;
public static final int SW = 6;
public static final int SOUTH = 7;
public static final int SE = 8;
private Controller controller;
private Component[] comps; // holds the components
// comps[] indices for specific components
private int xAxisIdx, yAxisIdx, zAxisIdx, rzAxisIdx;
// indices for the analog sticks axes
private int povIdx; // index for the POV hat
private int buttonsIdx[]; // indices for the buttons
private Rumbler[] rumblers;
private int rumblerIdx; // index for the rumbler being used
private boolean rumblerOn = false; // whether rumbler is on or off
public GamePadController()
{
// get the controllers
ControllerEnvironment ce =
ControllerEnvironment.getDefaultEnvironment();
Controller[] cs = ce.getControllers();
if (cs.length == 0) {
System.out.println("No controllers found");
System.exit(0);
}
else
System.out.println("Num. controllers: " + cs.length);
// get the game pad controller
controller = findGamePad(cs);
System.out.println("Game controller: " +
controller.getName() + ", " +
controller.getType());
// collect indices for the required game pad components
findCompIndices(controller);
findRumblers(controller);
} // end of GamePadController()
private Controller findGamePad(Controller[] cs)
/* Search the array of controllers until a suitable game pad
controller is found (eith of type GAMEPAD or STICK).
*/
{
Controller.Type type;
int i = 0;
while(i < cs.length) {
type = cs[i].getType();
if ((type == Controller.Type.GAMEPAD) ||
(type == Controller.Type.STICK))
break;
i++;
}
if (i == cs.length) {
System.out.println("No game pad found");
System.exit(0);
}
else
System.out.println("Game pad index: " + i);
return cs[i];
} // end of findGamePad()
private void findCompIndices(Controller controller)
/* Store the indices for the analog sticks axes
(x,y) and (z,rz), POV hat, and
button components of the controller.
*/
{
comps = controller.getComponents();
if (comps.length == 0) {
System.out.println("No Components found");
System.exit(0);
}
else
System.out.println("Num. Components: " + comps.length);
// get the indices for the axes of the analog sticks: (x,y) and (z,rz)
xAxisIdx = findCompIndex(comps, Component.Identifier.Axis.X, "x-axis");
yAxisIdx = findCompIndex(comps, Component.Identifier.Axis.Y, "y-axis");
zAxisIdx = findCompIndex(comps, Component.Identifier.Axis.Z, "z-axis");
rzAxisIdx = findCompIndex(comps, Component.Identifier.Axis.RZ, "rz-axis");
// get POV hat index
povIdx = findCompIndex(comps, Component.Identifier.Axis.POV, "POV hat");
findButtons(comps);
} // end of findCompIndices()
private int findCompIndex(Component[] comps,
Component.Identifier id, String nm)
/* Search through comps[] for id, returning the corresponding
array index, or -1 */
{
Component c;
for(int i=0; i < comps.length; i++) {
c = comps[i];
if ((c.getIdentifier() == id) && !c.isRelative()) {
System.out.println("Found " + c.getName() + "; index: " + i);
return i;
}
}
System.out.println("No " + nm + " component found");
return -1;
} // end of findCompIndex()
private void findButtons(Component[] comps)
/* Search through comps[] for NUM_BUTTONS buttons, storing
their indices in buttonsIdx[]. Ignore excessive buttons.
If there aren't enough buttons, then fill the empty spots in
buttonsIdx[] with -1's. */
{
buttonsIdx = new int[NUM_BUTTONS];
int numButtons = 0;
Component c;
for(int i=0; i < comps.length; i++) {
c = comps[i];
if (isButton(c)) { // deal with a button
if (numButtons == NUM_BUTTONS) // already enough buttons
System.out.println("Found an extra button; index: " + i + ". Ignoring it");
else {
buttonsIdx[numButtons] = i; // store button index
System.out.println("Found " + c.getName() + "; index: " + i);
numButtons++;
}
}
}
// fill empty spots in buttonsIdx[] with -1's
if (numButtons < NUM_BUTTONS) {
System.out.println("Too few buttons (" + numButtons +
"); expecting " + NUM_BUTTONS);
while (numButtons < NUM_BUTTONS) {
buttonsIdx[numButtons] = -1;
numButtons++;
}
}
} // end of findButtons()
private boolean isButton(Component c)
/* Return true if the component is a digital/absolute button, and
its identifier name ends with "Button" (i.e. the
identifier class is Component.Identifier.Button).
*/
{
if (!c.isAnalog() && !c.isRelative()) { // digital and absolute
String className = c.getIdentifier().getClass().getName();
// System.out.println(c.getName() + " identifier: " + className);
if (className.endsWith("Button"))
return true;
}
return false;
} // end of isButton()
private void findRumblers(Controller controller)
/* Find the rumblers. Use the last rumbler for making vibrations,
an arbitrary decision. */
{
// get the game pad's rumblers
rumblers = controller.getRumblers();
if (rumblers.length == 0) {
System.out.println("No Rumblers found");
rumblerIdx = -1;
}
else {
System.out.println("Rumblers found: " + rumblers.length);
rumblerIdx = rumblers.length-1; // use last rumbler
}
} // end of findRumblers()
// ----------------- polling and getting data ------------------
public void poll()
// update the component values in the controller
{
controller.poll();
}
public int getXYStickDir()
// return the (x,y) analog stick compass direction
{
if ((xAxisIdx == -1) || (yAxisIdx == -1)) {
System.out.println("(x,y) axis data unavailable");
return NONE;
}
else
return getCompassDir(xAxisIdx, yAxisIdx);
} // end of getXYStickDir()
public int getZRZStickDir()
// return the (z,rz) analog stick compass direction
{
if ((zAxisIdx == -1) || (rzAxisIdx == -1)) {
System.out.println("(z,rz) axis data unavailable");
return NONE;
}
else
return getCompassDir(zAxisIdx, rzAxisIdx);
} // end of getXYStickDir()
private int getCompassDir(int xA, int yA)
// Return the axes as a single compass value
{
float xCoord = comps[ xA ].getPollData();
float yCoord = comps[ yA ].getPollData();
// System.out.println("(x,y): (" + xCoord + "," + yCoord + ")");
int xc = Math.round(xCoord);
int yc = Math.round(yCoord);
// System.out.println("Rounded (x,y): (" + xc + "," + yc + ")");
if ((yc == -1) && (xc == -1)) // (y,x)
return NW;
else if ((yc == -1) && (xc == 0))
return NORTH;
else if ((yc == -1) && (xc == 1))
return NE;
else if ((yc == 0) && (xc == -1))
return WEST;
else if ((yc == 0) && (xc == 0))
return NONE;
else if ((yc == 0) && (xc == 1))
return EAST;
else if ((yc == 1) && (xc == -1))
return SW;
else if ((yc == 1) && (xc == 0))
return SOUTH;
else if ((yc == 1) && (xc == 1))
return SE;
else {
System.out.println("Unknown (x,y): (" + xc + "," + yc + ")");
return NONE;
}
} // end of getCompassDir()
public int getHatDir()
// Return the POV hat's direction as a compass direction
{
if (povIdx == -1) {
System.out.println("POV hat data unavailable");
return NONE;
}
else {
float povDir = comps[povIdx].getPollData();
if (povDir == POV.CENTER) // 0.0f
return NONE;
else if (povDir == POV.DOWN) // 0.75f
return SOUTH;
else if (povDir == POV.DOWN_LEFT) // 0.875f
return SW;
else if (povDir == POV.DOWN_RIGHT) // 0.625f
return SE;
else if (povDir == POV.LEFT) // 1.0f
return WEST;
else if (povDir == POV.RIGHT) // 0.5f
return EAST;
else if (povDir == POV.UP) // 0.25f
return NORTH;
else if (povDir == POV.UP_LEFT) // 0.125f
return NW;
else if (povDir == POV.UP_RIGHT) // 0.375f
return NE;
else { // assume center
System.out.println("POV hat value out of range: " + povDir);
return NONE;
}
}
} // end of getHatDir()
public boolean[] getButtons()
/* Return all the buttons in a single array. Each button value is
a boolean. */
{
boolean[] buttons = new boolean[NUM_BUTTONS];
float value;
for(int i=0; i < NUM_BUTTONS; i++) {
value = comps[ buttonsIdx[i] ].getPollData();
buttons[i] = ((value == 0.0f) ? false : true);
}
return buttons;
} // end of getButtons()
public boolean isButtonPressed(int pos)
/* Return the button value (a boolean) for button number 'pos'.
pos is in the range 1-NUM_BUTTONS to match the game pad
button labels.
*/
{
if ((pos < 1) || (pos > NUM_BUTTONS)) {
System.out.println("Button position out of range (1-" +
NUM_BUTTONS + "): " + pos);
return false;
}
if (buttonsIdx[pos-1] == -1) // no button found at that pos
return false;
float value = comps[ buttonsIdx[pos-1] ].getPollData();
// array range is 0-NUM_BUTTONS-1
return ((value == 0.0f) ? false : true);
} // end of isButtonPressed()
// ------------------- Trigger a rumbler -------------------
public void setRumbler(boolean switchOn)
// turn the rumbler on or off
{
if (rumblerIdx != -1) {
if (switchOn)
rumblers[rumblerIdx].rumble(0.8f); // almost full on for last rumbler
else // switch off
rumblers[rumblerIdx].rumble(0.0f);
rumblerOn = switchOn; // record rumbler's new status
}
} // end of setRumbler()
public boolean isRumblerOn()
{ return rumblerOn; }
} // end of GamePadController class
I think you are using the wrong design pattern here. You should use the observer pattern for this type of thing.
A polling loop not very efficient, and as you've noticed doesn't really yield the desired results.
I'm not sure what you are using inside your objects to detect if a key is pressed, but if it's a GUI architecture such as Swing or AWT it will be based on the observer pattern via the use of EventListeners, etc.
Here is a (slightly simplified) Observer-pattern
applied to your situation.
The advantage of this design is that when a button
is pressed and hold, method 'buttonChanged' will
still only be called once, instead of start
'repeating' every 50 ms.
public static final int BUTTON_01 = 0x00000001;
public static final int BUTTON_02 = 0x00000002;
public static final int BUTTON_03 = 0x00000004;
public static final int BUTTON_04 = 0x00000008; // hex 8 == dec 8
public static final int BUTTON_05 = 0x00000010; // hex 10 == dec 16
public static final int BUTTON_06 = 0x00000020; // hex 20 == dec 32
public static final int BUTTON_07 = 0x00000040; // hex 40 == dec 64
public static final int BUTTON_08 = 0x00000080; // etc.
public static final int BUTTON_09 = 0x00000100;
public static final int BUTTON_10 = 0x00000200;
public static final int BUTTON_11 = 0x00000400;
public static final int BUTTON_12 = 0x00000800;
private int previousButtons = 0;
void poll()
{
rockbandDrum.poll();
handleButtons();
}
private void handleButtons()
{
boolean[] buttons = getButtons();
int pressedButtons = getPressedButtons(buttons);
if (pressedButtons != previousButtons)
{
buttonChanged(pressedButtons); // Notify 'listener'.
previousButtons = pressedButtons;
}
}
public boolean[] getButtons()
{
// Return all the buttons in a single array. Each button-value is a boolean.
boolean[] buttons = new boolean[MAX_NUMBER_OF_BUTTONS];
float value;
for (int i = 0; i < MAX_NUMBER_OF_BUTTONS-1; i++)
{
int index = buttonsIndex[i];
if (index < 0) { continue; }
value = comps[index].getPollData();
buttons[i] = ((value == 0.0f) ? false : true);
}
return buttons;
}
private int getPressedButtons(boolean[] array)
{
// Mold all pressed buttons into a single number by OR-ing their values.
int pressedButtons = 0;
int i = 1;
for (boolean isBbuttonPressed : array)
{
if (isBbuttonPressed) { pressedButtons |= getOrValue(i); }
i++;
}
return pressedButtons;
}
private int getOrValue(int btnNumber) // Get a value to 'OR' with.
{
int btnValue = 0;
switch (btnNumber)
{
case 1 : btnValue = BUTTON_01; break;
case 2 : btnValue = BUTTON_02; break;
case 3 : btnValue = BUTTON_03; break;
case 4 : btnValue = BUTTON_04; break;
case 5 : btnValue = BUTTON_05; break;
case 6 : btnValue = BUTTON_06; break;
case 7 : btnValue = BUTTON_07; break;
case 8 : btnValue = BUTTON_08; break;
case 9 : btnValue = BUTTON_09; break;
case 10 : btnValue = BUTTON_10; break;
case 11 : btnValue = BUTTON_11; break;
case 12 : btnValue = BUTTON_12; break;
default : assert false : "Invalid button-number";
}
return btnValue;
}
public static boolean checkButton(int pressedButtons, int buttonToCheckFor)
{
return (pressedButtons & buttonToCheckFor) == buttonToCheckFor;
}
public void buttonChanged(int buttons)
{
if (checkButton(buttons, BUTTON_01)
{
drum.playSound("hiHat.wav");
}
if (checkButton(buttons, BUTTON_02)
{
drum.playSound("crash.wav");
}
}
Please post more information about the GamePadController class that you are using.
More than likely, that same library will offer an "event" API, where a "callback" that you register with a game pad object will be called as soon as the user presses a button. With this kind of setup, the "polling" loop is in the framework, not your application, and it can be much more efficient, because it uses signals from the hardware rather than a busy-wait polling loop.
Okay, I looked at the JInput API, and it is not really event-driven; you have to poll it as you are doing. Does the sound stop looping when you release the button? If so, is your goal to have the sound play just once, and not again until the button is release and pressed again? In that case, you'll need to track the previous button state each time through the loop.
Human response time is about 250 ms (for an old guy like me, anyway). If you are polling every 50 ms, I'd expect the controller to report the button depressed for several iterations of the loop. Can you try something like this:
boolean played = false;
while (true) {
String sound = null;
if (controller.isButtonPressed(1))
sound = "hiHat.wav";
if (controller.isButtonPressed(2))
sound = "crash.wav";
if (sound != null) {
if (!played) {
drum.playSound(sound);
played = true;
}
} else {
played = false;
}
Thread.sleep(50);
}