How to immediate greater and smaller value and select the value? - java

I have a scenario to take the maximum value from the nearest number and match with that number with .if it is match click action would perform..all conditions I put it in a for loop..
public static int insertBeforeAfterMethod(int i, String event, String shotType, WindowsDriver < WebElement > mainEntrySession) {
for(int cellIndex = 14;cellIndex < pbp_insert_grid_cells.size();cellIndex+=17) //
{
System.out.println(pbp_insert_grid_cells.size());
rowSequenceNo = pbp_insert_grid_cells.get(cellIndex).getText();
String[] splitvalue=rowSequenceNo.split("\\.");
int guiSequenceNo=Integer.parseInt(splitvalue[0]);
System.out.println("hello gui sequence number....."+guiSequenceNo);
//i==4 here i==3
if ((i%2!=0) && (sequenceNo < guiSequenceNo)) //1.5 <2 insert before
{
System.out.println("hello"+i);
next =guiSequenceNo; //2
System.out.println("next"+next);
break;
}
else if((i%2==0) && (sequenceNo > guiSequenceNo)) //insert after
{
previous=guiSequenceNo;
break;
}
if(next==guiSequenceNo) // 2==rowSequenceNo insert before
{
System.out.println(cellIndex);
WebElement sequenceCellNoInsertBefore = mainEntrySession.findElementByName(pbp_insert_grid_cells.get(cellIndex).getAttribute("Name"));
rowNumber = sequenceCellNoInsertBefore.getAttribute("Name").substring(16);
System.out.println(rowNumber);
if(mainEntrySession.findElementByName(rowNumber).isDisplayed())
{
rowToClick = mainEntrySession.findElementByName("Period " +rowNumber);
rowToClick.click();
action.moveToElement(rowToClick).contextClick().perform();
mainEntrySession.findElementByName("Insert Before").click();
mainEntrySession.findElementByAccessibilityId("6").click();
retValue = getNexti(i, event,shotType,mainEntrySession);
System.out.println("return i "+retValue);
}
}
else if(previous==guiSequenceNo) //insert after
{
WebElement sequenceCellNoInsertAfter = mainEntrySession.findElementByName(pbp_insert_grid_cells.get(cellIndex).getAttribute("Name"));
rowNumber = sequenceCellNoInsertAfter.getAttribute("Name").substring(16);
System.out.println(rowNumber);
if(mainEntrySession.findElementByName(rowNumber).isDisplayed())
{
rowToClick = mainEntrySession.findElementByName("Period " +rowNumber);
rowToClick.click();
action.moveToElement(rowToClick).contextClick().perform();
mainEntrySession.findElementByName("Insert After").click();
mainEntrySession.findElementByAccessibilityId("6").click();
retValue = getNexti(i, event,shotType,mainEntrySession);
System.out.println("return i "+retValue);
}
}
}
return retValue;
}
here the for looping is not incrementing it is exiting...without break how to take immediate greater and smaller and store it in a variable...?

Related

Android - An algorithm to check recursively if a map is solvable

I am making an android Hashikawekero puzzle game, I have implemented a algorithm to spawn nodes (Islands) at random positions using a 2-d array this works fine it creates the node at random position but most of the times the map cant be solved. The map nodes spawn at random.
BoardCreation.java Class - this generates the map.
package Island_and_Bridges.Hashi;
import android.annotation.TargetApi;
import android.os.Build;
import android.util.Log;
import java.util.Random;
import static junit.framework.Assert.*;
//This class Creates the map by random using a 2d array
public class BoardCreation {
// This class member is used for random initialization purposes.
static private final Random random = new Random();
// The difficulty levels.
private static final int EASY = 0;
static public final int MEDIUM = 1;
static public final int HARD = 2;
static public final int EMPTY = 0;
private static int ConnectionFingerprint(BoardElement start, BoardElement end) {
int x = start.row * 100 + start.col;
int y = end.row * 100 + end.col;
// Swap to get always the same fingerprint independent whether we are called
// start-end or end-start
if (x > y ) {
int temp = x;
x = y;
y = temp;
}
Log.d("", String.format("%d %d" , x ,y));
return x ^ y;
}
public class State {
// The elements of the board are stored in this array.
// A value defined by "EMPTY" means that its not set yet.
public BoardElement [][] board_elements = null;
public int [][] cell_occupied = null;
// The width of the board. We only assume squared boards.
public int board_width=0;
public State(int width) {
board_width = width;
board_elements = new BoardElement[width][width];
cell_occupied = new int[width][width];
}
public State CloneWithoutConnections() {
State newstate = new State(board_width);
if (board_elements != null) {
newstate.board_elements = new BoardElement[board_elements.length][board_elements.length];
for (int i = 0; i < board_elements.length; ++i) {
for (int j = 0; j < board_elements.length; ++j) {
if (board_elements[i][j] == null)
continue;
newstate.board_elements[i][j] = board_elements[i][j].clone();
}
}
}
if (cell_occupied != null) {
assert board_elements != null;
newstate.cell_occupied = new int[board_elements.length][board_elements.length];
for (int i = 0; i < board_elements.length; ++i) {
System.arraycopy(cell_occupied[i], 0, newstate.cell_occupied[i], 0, board_elements.length);
}
}
return newstate;
}
public void AddToBridgeCache(BoardElement first, BoardElement second) {
if (first == null || second == null) { return; }
final int fingerprint = ConnectionFingerprint(first, second);
Log.d(getClass().getName(),
String.format("Fingerprint of this bridge %d", fingerprint));
// mark the end points as occupied.
cell_occupied[first.row][first.col] = fingerprint;
cell_occupied[second.row][second.col] = fingerprint;
int dcol = second.col - first.col;
int drow = second.row - first.row;
if (first.row == second.row) {
for (int i = (int) (first.col + Math.signum(dcol)); i != second.col; i += Math.signum(dcol)) {
cell_occupied[first.row][i] = fingerprint;
String.format("deleting bridge");
}
} else {
assert first.col == second.col;
for (int i = (int) (first.row + Math.signum(drow)); i != second.row; i+= Math.signum(drow)) {
cell_occupied[i][first.col] = fingerprint;
}
}
}
} // end of state
private State current_state, old_state;
static private final int WIDTH_EASY = 7;
private void NewGame(int hardness) {
switch(hardness) {
case EASY:
Log.d(getClass().getName(), "Initializing new easy game");
InitializeEasy();
old_state = getCurrentState().CloneWithoutConnections();
break;
}
}
public void ResetGame() {
if (old_state != null) {
Log.d(getClass().getName(), "Setting board_elements to old_elements");
setCurrentState(old_state.CloneWithoutConnections());
} else {
Log.d(getClass().getName(), "old_lements are zero");
}
}
public BoardCreation(int hardness) {
NewGame(hardness);
}
public boolean TryAddNewBridge(BoardElement start, BoardElement end, int count) {
assertEquals(count, 1);
assert (start != null);
assert (end != null);
final int fingerprint = ConnectionFingerprint(start, end);
Log.d(getClass().getName(),
String.format("considering (%d,%d) and (%d,%d)", start.row,start.col, end.row,end.col));
if (start.row == end.row && start.col == end.col) {
Log.d(getClass().getName(), "Same nodes selected!");
return false;
}
assert count > 0;
int dcol = end.col - start.col;
int drow = end.row - start.row;
// It must be a vertical or horizontal bridge:
if (Math.abs(dcol) > 0 && Math.abs(drow) > 0) {
Log.d(getClass().getName(), "not a horizontal or vertical bridge.");
return false;
}
// First we check whether start and end elements can take the specified bridge counts.
int count_start = start.GetCurrentCount();
int count_end = end.GetCurrentCount();
if (count_start + count > start.max_connecting_bridges ||
count_end + count > end.max_connecting_bridges) {
Log.d(getClass().getName(), "This Bridge is not allowed");
return false;
}
Log.d(getClass().getName(),
String.format("Sums:%d # (%d,%d) and %d # (%d,%d)",
count_start, start.row, start.col,
count_end, end.row, end.col));
Connection start_connection = null;
Connection end_connection = null;
// Next we check whether we are crossing any lines.
if (start.row == end.row) {
for (int i = (int) (start.col + Math.signum(dcol)); i != end.col; i += Math.signum(dcol)) {
if (getCurrentState().cell_occupied[start.row][i] > 0 &&
getCurrentState().cell_occupied[start.row][i] != fingerprint) {
Log.d(getClass().getName(), "Crossing an occupied cell.");
return false;
}
}
assert start.col != end.col;
if (start.col > end.col) {
start.connecting_east = GetOrCreateConnection(end, start.connecting_east);
end.connecting_west = GetOrCreateConnection(start, end.connecting_west);
start_connection = start.connecting_east;
end_connection = end.connecting_west;
} else {
start.connecting_west = GetOrCreateConnection(end, start.connecting_west);
end.connecting_east = GetOrCreateConnection(start, end.connecting_east);
start_connection = start.connecting_west;
end_connection = end.connecting_east;
}
} else {
assert start.col == end.col;
for (int i = (int) (start.row + Math.signum(drow)); i != end.row ; i += Math.signum(drow)) {
if (getCurrentState().cell_occupied[i][start.col] > 0 &&
getCurrentState().cell_occupied[i][start.col] != fingerprint) {
Log.d(getClass().getName(), "Crossing an occupied cell.");
return false;
}
}
if (start.row > end.row ) {
start.connecting_north = GetOrCreateConnection(end, start.connecting_north);
end.connecting_south = GetOrCreateConnection(start, end.connecting_south);
start_connection = start.connecting_north;
end_connection = end.connecting_south;
} else {
start.connecting_south= GetOrCreateConnection(end, start.connecting_south);
end.connecting_north = GetOrCreateConnection(start, end.connecting_north);
start_connection = start.connecting_south;
end_connection = end.connecting_north;
}
}
start_connection.destination = end;
end_connection.destination = start;
start_connection.second += count;
end_connection.second += count;
getCurrentState().AddToBridgeCache(start, end);
Log.d(getClass().getName(),
String.format("New bridge added. Sums:%d # (%d,%d) and %d # (%d,%d)",
count_start, start.row,start.col,
count_end, end.row,end.col));
return true;
}
private Connection GetOrCreateConnection(
BoardElement end,
Connection connection) {
if (connection!= null) { return connection; }
return new Connection();
}
#TargetApi(Build.VERSION_CODES.N)
private void InitializeEasy() {
Random rand = new Random();
String[][] debug_board_state = new String[7][7];
setCurrentState(new State(WIDTH_EASY));
for (int row = 0; row < debug_board_state.length; row++) {
for (int column = 0; column < debug_board_state[row].length; column++) {
debug_board_state[row][column] = String.valueOf(rand.nextInt(5));
}
}
for (int row = 0; row < debug_board_state.length; row++) {
for (int column = 0; column < debug_board_state[row].length; column++) {
System.out.print(debug_board_state[row][column] + " ");
}
System.out.println();
}
for (int row = 0; row < WIDTH_EASY; ++row) {
for (int column = 0; column < WIDTH_EASY; ++column) {
getCurrentState().board_elements[row][column] = new BoardElement();
getCurrentState().board_elements[row][column].max_connecting_bridges = Integer.parseInt(debug_board_state[row][column]);
getCurrentState().board_elements[row][column].row = row;
getCurrentState().board_elements[row][column].col = column;
if (getCurrentState().board_elements[row][column].max_connecting_bridges > 0) {
getCurrentState().board_elements[row][column].is_island = true;
}
}
}
}
private void setCurrentState(State new_state) {
this.current_state = new_state;
}
public State getCurrentState() {
return current_state;
}
}
What algorithm could I use to make sure the Map can be Solved (Islands Connected with Bridges) before spawning the nodes.
This is what the map looks like (don't mind the design)
One thing to consider would be to start with a blank board. Place an island. Then place another island that can be connected to the first one (i.e. on one of the four cardinal directions). Connect the two with a bridge, and increment each island's count.
Now, pick one of the two islands and place another island that it can connect. Add the bridge and increment.
Continue in this way until you've placed the number of islands that you want to place.
The beauty here is that you start with an empty board, and during construction the board is always valid.
You'll have to ensure that you're not crossing bridges when you place new islands, but that's pretty easy to do, since you know where the existing bridges are.

Why do object arrays in my ArrayList fail to retain their values?

I am creating a program in Java to simulate evolution. The way I have it set up, each generation is composed of an array of Organism objects. Each of these arrays is an element in the ArrayList orgGenerations. Each generation, of which there could be any amount before all animals die, can have any amount of Organism objects.
For some reason, in my main loop when the generations are going by, I can have this code without errors, where allOrgs is the Organism array of the current generation and generationNumber is the number generations since the first.
orgGenerations.add(allOrgs);
printOrgs(orgGenerations.get(generationNumber));
printOrgs is a method to display an Organism array, where speed and strength are Organism Field variables:
public void printOrgs(Organism[] list)
{
for (int x=0; x<list.length; x++)
{
System.out.println ("For organism number: " + x + ", speed is: " + list[x].speed + ", and strength is " + list[x].strength + ".");
}
}
Later on, after this loop, when I am trying to retrieve the data to display, I call this very similar code:
printOrgs(orgGenerations.get(0));
This, and every other array in orgGenerations, return a null pointer exception on the print line of the for loop. Why are the Organism objects loosing their values?
Alright, here is all of the code from my main Simulation class. I admit, it might be sort of a mess. The parts that matter are the start and simulator methods. The battle ones are not really applicable to this problem. I think.
import java.awt.FlowLayout;
import java.util.*;
import javax.swing.JFrame;
public class Simulator {
//variables for general keeping track
static Organism[] allOrgs;
static ArrayList<Organism[]> orgGenerations = new ArrayList <Organism[]>();
ArrayList<Integer> battleList = new ArrayList<Integer>();
int deathCount;
boolean done;
boolean runOnce;
//setup
Simulator()
{
done = false;
Scanner asker = new Scanner(System.in);
System.out.println("Input number of organisms for the simulation: ");
int numOfOrgs = asker.nextInt();
asker.close();
Organism[] orgArray = new Organism[numOfOrgs];
for (int i=0; i<numOfOrgs; i++)
{
orgArray[i] = new Organism();
}
allOrgs = orgArray;
}
//graphsOrgs
public void graphOrgs() throws InterruptedException
{
JFrame f = new JFrame("Evolution");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(1000,500);
f.setVisible(true);
Drawer bars = new Drawer();
//System.out.println(orgGenerations.size());
for (int iterator=0;iterator<(orgGenerations.size()-1); iterator++)
{
printOrgs(orgGenerations.get(0));
//The 0 can be any number, no matter what I do it wont work
//System.out.println("first");
f.repaint();
bars.data = orgGenerations.get(iterator);
f.add(bars);
//System.out.println("before");
Thread.sleep(1000);
//System.out.println("end");
}
}
//prints all Orgs and their statistics
public void printOrgs(Organism[] list)
{
System.out.println("Number Of Organisms: " + list.length);
for (int x=0; x<list.length; x++)
{
System.out.println ("For organism number: " + x + ", speed is: " + list[x].speed + ", and strength is " + list[x].strength + ".");
}
System.out.println();
}
//general loop for the organisms lives
public void start(int reproductionTime) throws InterruptedException
{
int generationNumber = 0;
orgGenerations.add(allOrgs);
printOrgs(orgGenerations.get(0));
generationNumber++;
while(true)
{
deathCount = 0;
for(int j=0; j<reproductionTime; j++)
{
battleList.clear();
for(int m=0; m<allOrgs.length; m++)
{
if (allOrgs[m].alive == true)
oneYearBattleCheck(m);
}
battle();
}
reproduction();
if (done == true)
break;
orgGenerations.add(allOrgs);
printOrgs(orgGenerations.get(generationNumber));
generationNumber++;
}
printOrgs(orgGenerations.get(2));
}
//Checks if they have to fight this year
private void oneYearBattleCheck(int m)
{
Random chaos = new Random();
int speedMod = chaos.nextInt(((int)Math.ceil(allOrgs[m].speed/5.0))+1);
int speedSign = chaos.nextInt(2);
if (speedSign == 0)
speedSign--;
speedMod *= speedSign;
int speed = speedMod + allOrgs[m].speed;
if (speed <= 0)
speed=1;
Random encounter = new Random();
boolean battle = false;
int try1 =(encounter.nextInt(speed));
int try2 =(encounter.nextInt(speed));
int try3 =(encounter.nextInt(speed));
int try4 =(encounter.nextInt(speed));
if (try1 == 0 || try2 == 0 || try3 == 0 || try4 == 0 )
{
battle = true;
}
if(battle == true)
{
battleList.add(m);
}
}
//Creates the matches and runs the battle
private void battle()
{
Random rand = new Random();
if (battleList.size()%2 == 1)
{
int luckyDuck = rand.nextInt(battleList.size());
battleList.remove(luckyDuck);
}
for(int k=0; k<(battleList.size()-1);)
{
int competitor1 = rand.nextInt(battleList.size());
battleList.remove(competitor1);
int competitor2 = rand.nextInt(battleList.size());
battleList.remove(competitor2);
//Competitor 1 strength
int strengthMod = rand.nextInt(((int)Math.ceil(allOrgs[competitor1].strength/5.0))+1);
int strengthSign = rand.nextInt(2);
if (strengthSign == 0)
strengthSign--;
strengthMod *= strengthSign;
int comp1Strength = strengthMod + allOrgs[competitor1].strength;
//Competitor 2 strength
strengthMod = rand.nextInt(((int)Math.ceil(allOrgs[competitor2].strength/5.0))+1);
strengthSign = rand.nextInt(2);
if (strengthSign == 0)
strengthSign--;
strengthMod *= strengthSign;
int comp2Strength = strengthMod + allOrgs[competitor2].strength;
//Fight!
if (comp1Strength>comp2Strength)
{
allOrgs[competitor1].life ++;
allOrgs[competitor2].life --;
}
else if (comp2Strength>comp1Strength)
{
allOrgs[competitor2].life ++;
allOrgs[competitor1].life --;
}
if (allOrgs[competitor1].life == 0)
{
allOrgs[competitor1].alive = false;
deathCount++;
}
if (allOrgs[competitor2].life == 0)
{
allOrgs[competitor2].alive = false;
deathCount ++ ;
}
}
}
//New organisms
private void reproduction()
{
//System.out.println("Number of deaths: " + deathCount + "\n");
if (deathCount>=(allOrgs.length-2))
{
done = true;
return;
}
ArrayList<Organism> tempOrgs = new ArrayList<Organism>();
Random chooser = new Random();
int count = 0;
while(true)
{
int partner1 = 0;
int partner2 = 0;
boolean partnerIsAlive = false;
boolean unluckyDuck = false;
//choose partner1
while (partnerIsAlive == false)
{
partner1 = chooser.nextInt(allOrgs.length);
if (allOrgs[partner1] != null)
{
if (allOrgs[partner1].alive == true)
{
partnerIsAlive = true;
}
}
}
count++;
//System.out.println("Count 2: " + count);
partnerIsAlive = false;
//choose partner2
while (partnerIsAlive == false)
{
if (count+deathCount == (allOrgs.length))
{
unluckyDuck=true;
break;
}
partner2 = chooser.nextInt(allOrgs.length);
if (allOrgs[partner2] != null)
{
if (allOrgs[partner2].alive == true)
{
partnerIsAlive = true;
}
}
}
if (unluckyDuck == false)
count++;
//System.out.println("count 2: " + count);
if (unluckyDuck == false)
{
int numOfChildren = (chooser.nextInt(4)+1);
for (int d=0; d<numOfChildren; d++)
{
tempOrgs.add(new Organism(allOrgs[partner1].speed, allOrgs[partner2].speed, allOrgs[partner1].strength, allOrgs[partner2].strength ));
}
allOrgs[partner1] = null;
allOrgs[partner2] = null;
}
if (count+deathCount == (allOrgs.length))
{
Arrays.fill(allOrgs, null);
allOrgs = tempOrgs.toArray(new Organism[tempOrgs.size()-1]);
break;
}
//System.out.println(count);
}
}
}
Main method:
public class Runner {
public static void main(String[] args) throws InterruptedException {
Simulator sim = new Simulator();
int lifeSpan = 20;
sim.start(lifeSpan);
sim.graphOrgs();
}
}
Organism class:
import java.util.Random;
public class Organism {
static Random traitGenerator = new Random();
int life;
int speed;
int strength;
boolean alive;
Organism()
{
speed = (traitGenerator.nextInt(49)+1);
strength = (50-speed);
life = 5;
alive = true;
}
Organism(int strength1, int strength2, int speed1, int speed2)
{
Random gen = new Random();
int speedMod = gen.nextInt(((int)Math.ceil((speed1+speed2)/10.0))+1);
int speedSign = gen.nextInt(2);
if (speedSign == 0)
speedSign--;
speedMod *= speedSign;
//System.out.println(speedMod);
int strengthMod = gen.nextInt(((int)Math.ceil((strength1+strength2)/10.0))+1);
int strengthSign = gen.nextInt(2);
if (strengthSign == 0)
strengthSign--;
strengthMod *= strengthSign;
//System.out.println(strengthMod);
strength = (((int)((strength1+strength2)/2.0))+ strengthMod);
speed = (((int)((speed1+speed2)/2.0))+ speedMod);
alive = true;
life = 5;
}
}
The problem lies in the graphOrgs class when I try to print to check if it is working in preparation for graphing the results. This is when it returns the error. When I try placing the print code in other places in the Simulator class the same thing occurs, a null pointer error. This happens even if it is just after the for loop where the element has been established.
You have code that sets to null elements in your allOrgs array.
allOrgs[partner1] = null;
allOrgs[partner2] = null;
Your orgGenerations list contains the same allOrgs instance multiple times.
Therefore, when you write allOrgs[partner1] = null, the partner1'th element becomes null in all the list elements of orgGenerations, which is why the print method fails.
You should create a copy of the array (you can use Arrays.copy) each time you add a new generation to the list (and consider also creating copies of the Organism instances, if you want each generation to record the past state of the Organisms and not their final state).

match and delete elements in arraylists

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.

Text file load error and array error on mouse island application

I have a problem, I am not looking for answers to my problem I would like some help finding why my array even though specified in main unders switch: case1, case2, case3. I used a for loops with an array that stops at the 5th iteration. However when I run the program it only runs once, am I specifying correctly to make it run 5 times or should it be declared another way? thanks in advance. I should also include there are no errors reported by eclipse at this time until it is ran and only after the first input.
The text files contains
##B##
#---#
#-M-#
#---#
##B##
##B##########
#-----------#
#-----------#
#-----------B
#-----------#
#------M----#
#-----------#
#-----------#
#-----------#
#-----------#
#-----------#
#-----------#
#############
##B#####
#------#
#-M----#
#------#
#------#
#------#
#------#
#####B##
The island maps can be found here
[http://rapidshare.com/share/9704FE33EFF98F1C1E71F6F1DF2DC0D4]
This is the array (int i=0;i<5;i++) however I do not think this is the problem, I can also provide the text files if needed
This is the console out
CS1181 Mouse Island
1. mouseIsland1.txt
2. mouseIsland2.txt
3. mouseIsland3.txt
9. Exit
Please make your selection: 2
Filename: mouseIsland2.txt
Bridge1: 0,0
Bridge2: 0,0
Mouse: 0,0
OUCH! The Mouse fell into the water and died at: 1|1
01
0100000000000
0000000000000
0000000000000
0000000000000
0000000000000
0000000000000
0000000000000
0000000000000
0000000000000
0000000000000
0000000000000
0000000000000
0000000000000
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at MouseEscape.runMouseIsland(MouseEscape.java:349)
at MouseEscape.main(MouseEscape.java:71)
End console
import java.io.File;
import java.util.Scanner;
public class MouseEscape {
public static Scanner input = new Scanner(System.in);
public static MouseEscape island1;
public static MouseEscape island2;
public static MouseEscape island3;
private String islandTxt;
private boolean moveDebug;
private int mouseEscaped;
private int mouseDrowned;
private int mouseStarved;
private int islandRows;
private int [] islandCols;
private int runCount;
private int [][] mousePosition;
private int [][] bridgePosition;
private int [][] islandIntArray;
private char [][] islandCharArray;
// main
// Allows the user to select which mouse island map to simulate
public static void main(String[] args) throws Exception
{
System.out.println("CS1181 Mouse Island");
int choice = 0, continueRun = 1;
boolean runResponce = false, correctInput = false;
while (continueRun == 1)
{
System.out.print("\n 1. mouseIsland1.txt"
+ "\n 2. mouseIsland2.txt"
+ "\n 3. mouseIsland3.txt"
+ "\n 9. Exit\n\nPlease make your selection: ");
continueRun = 9;
runResponce = false;
while (correctInput == false){
while (!input.hasNextInt()) {
input.next();
System.out.print("Enter a number 1-3 or 9 to exit.\nPlease make your selection: ");
}
choice = input.nextInt();
if (choice>=1 && choice <=3 || choice == 9){
correctInput = true;
break;
}
}
switch(choice)
{
case 1:
MouseEscape island1 = new MouseEscape("mouseIsland1.txt");
System.out.println("\nFilename: "+island1.getIslandTxt()
+"\nBridge1: "+island1.getBridgePosition(0,0)+","+island1.getBridgePosition(0,1)
+"\nBridge2: "+island1.getBridgePosition(1,0)+","+island1.getBridgePosition(1,1)
+"\nMouse: "+island1.getMousePosition(1,0)+","+island1.getMousePosition(1,1)+"\n");
//island1.drawCharIsland();
for (int i=0;i<5;i++) island1.runMouseIsland();
island1.printIslandStats();
correctInput=false; continueRun=1; break;
case 2:
MouseEscape island2 = new MouseEscape("mouseIsland2.txt");
System.out.println("\nFilename: "+island2.getIslandTxt()
+"\nBridge1: "+island2.getBridgePosition(0,0)+","+island2.getBridgePosition(0,1)
+"\nBridge2: "+island2.getBridgePosition(1,0)+","+island2.getBridgePosition(1,1)
+"\nMouse: "+island2.getMousePosition(1,0)+","+island2.getMousePosition(1,1)+"\n");
//island1.drawCharIsland();
for (int i=0;i<5;i++) island2.runMouseIsland();
island2.printIslandStats();
correctInput=false; continueRun=1; break;
case 3:
MouseEscape island3 = new MouseEscape("mouseIsland3.txt");
System.out.println("\nFilename: "+island3.getIslandTxt()
+"\nBridge1: "+island3.getBridgePosition(0,0)+","+island3.getBridgePosition(0,1)
+"\nBridge2: "+island3.getBridgePosition(1,0)+","+island3.getBridgePosition(1,1)
+"\nMouse: "+island3.getMousePosition(1,0)+","+island3.getMousePosition(1,1)+"\n");
//island1.drawCharIsland();
for (int i=0;i<5;i++) island3.runMouseIsland();
island3.printIslandStats();
correctInput=false; continueRun=1; break;
}
if (runResponce == false)
{
if (continueRun == 1)
{
runResponce = true;
correctInput = false;
}
}
}
input.close();
}
// MouseIslandClass
// Constructs a mouseIslandClass without specifying which mouseIsland to load
public MouseEscape() {
islandTxt = "";
mouseEscaped = 0;
mouseDrowned = 0;
mouseStarved = 0;
islandRows = 0;
runCount = 0;
mousePosition = null;
bridgePosition = null;
islandIntArray = null;
islandCharArray = null;
}
// MouseIslandClass
// Constructs a mouseIslandClass given a mouseIsland map name
public MouseEscape(String _islandTxt) throws Exception{
islandTxt = _islandTxt;
loadIsland();
}
// setIslandTxt
// Sets the mouseIsland filename for the current mouseIsland
public void setIslandTxt(String _islandTxt) throws Exception{
islandTxt = _islandTxt;
}
// getIslandTxt
// Gets the mouseIsland filename for the current mouseIsland
public String getIslandTxt(){
return islandTxt;
}
// getMouseEscaped
// Returns the total number of times a mouse has escaped from the current mouseIsland
public int getMouseEscaped(){
return mouseEscaped;
}
// getMouseDrowned
// Returns the total number of times a mouse has drowned on the current mouseIsland
public int getMouseDrowned(){
return mouseDrowned;
}
// getMouseStarved
// Returns the total number of times a mouse has starved on the current mouseIsland
public int getMouseStarved(){
return mouseStarved;
}
// getBridgePosition
// Returns the coordinate row(x) or column(y) to either of the bridges on the current mouseIsland
public int getBridgePosition(int x, int y){
return bridgePosition[x][y];
}
// getMousePosition
// Returns the coordinate row(x) or column(y) of the mouse on the current mouseIsland
public int getMousePosition(int x, int y){
return mousePosition[x][y];
}
// loadIsland
// Populates any information needed to run the simulation for the current mouseIsland
public void loadIsland() throws Exception{
if (islandTxt == "" || islandTxt == null){
System.out.println("loadIsland() failed! 'islandTxt' variable is empty!");
return;
}
findIslandRow();
findIslandCol();
setCharIslandArray();
findIslandVariables();
}
// printIslandStats
// Prints to the console the statistics for this mouseIsland at its current state
public void printIslandStats(){
System.out.println("Run count: " + runCount + " times\n"
+ "Drowned: " + mouseDrowned + " times\n"
+ "Starved: " + mouseStarved + " times\n"
+ "Escaped: " + mouseEscaped + " times \n");
}
// maxValue
// This function returns the max value of an integer array.
public int maxValue(int [] inArray){
int value = 0;
for (int i=0;i<inArray.length;i++)
if (value<inArray[i]) value = inArray[i];
return value;
}
// findIslandRow
// Counts the number of rows for the current mouseIsland
public void findIslandRow() throws Exception {
Scanner input = new Scanner(new File(islandTxt));
islandRows = 0;
while(input.hasNext()){
input.nextLine();
islandRows++;
}
//System.out.println("Rows: "+islandRows);
input.close();
}
// findIslandCol
// Counts and stores the number of columns for each row in the current mouseIsland
public void findIslandCol() throws Exception {
Scanner input = new Scanner(new File(islandTxt));
String inputLine = ""; int row = 0; islandCols = new int [islandRows];
while(input.hasNext()){
inputLine = input.nextLine();
islandCols[row] = inputLine.length();
//System.out.println("Col"+row+": "+islandCols[row]);
row++;
}
input.close();
}
// loads a mouse island map into a 2 dimensional character array
public void setCharIslandArray() throws Exception {
Scanner input = new Scanner(new File(islandTxt));
islandCharArray = new char [islandRows+1][maxValue(islandCols)+1];
String islandRow ="";
for(int row=0;row<islandRows;row++){
islandRow = input.nextLine();
for (int col=0;col<islandRow.length();col++) {
islandCharArray[row][col] = islandRow.charAt(col);
}
}
input.close();
}
// drawCharIsland
// Draws a character array to the console for testing
public void drawCharIsland() throws Exception{
String ln = "";
for (int row= 0;row<islandRows;row++){
for (int col= 0;col<islandCols[row];col++){
if (col == islandCols[row]-1) ln = "\n"; else ln ="";
System.out.print(islandCharArray[row][col]+ln);
}
}
System.out.println("");
}
// drawIntIsland
// Draws an integer array to the console for testing
public void drawIntIsland() throws Exception{
String ln = "";
for (int row= 0;row<islandRows;row++){
for (int col= 0;col<islandCols[row];col++){
if (col == islandCols[row]-1) ln = "\n"; else ln ="";
System.out.print(islandIntArray[row][col]+ln);
}
}
System.out.println("");
}
// drawBigIntIsland
// Draws an integer array with special formatting for larger numbers the console for testing
public void drawBigIntIsland() throws Exception{
String ln = ""; String rowZero = ""; String colZero = "";
int i=0;
for (int row= 0;row<islandRows;row++){
if (row <= 9) rowZero = " "; else rowZero ="";
for (int col= 0;col<islandCols[row];col++){
if (row == 0)
while (i<islandRows){
if (i == 0) System.out.print("XY");
if (i <= 9) colZero = " "; else colZero ="";
if (i == islandCols[row]-1) ln = "\n"; else ln ="";
System.out.print(colZero+i+ln);
i++;
}
if (col == islandCols[row]-1) ln = "\n"; else ln ="";
if (islandIntArray[row][col] <= 9) colZero = "|"; else colZero ="";
if (col == 0) System.out.print(rowZero+row);
if (row >=0 && col >=0) System.out.print(colZero+islandIntArray[row][col]+ln);
}
}
}
// findIslandVariables
// finds and stores all of the mouseIsland object variables
public void findIslandVariables() throws Exception{
int bCount = 0;
mousePosition = new int [2][2]; bridgePosition = new int [200][2];
for (int row= 0;row<islandRows;row++){
for (int col= 0;col<islandCols[row];col++){
//System.out.println(row+"|"+col);
switch(islandCharArray[row][col]) {
case 'X' : mousePosition[0][0] = row; mousePosition[0][1] = col; //current position
mousePosition[1][0] = row; mousePosition[1][1] = col; //start position
//System.out.println("Mouse found on: "+row+"|"+col);
break;
case '-' :
if (row == 0 || col == 0 || row == islandRows-1 || col == islandCols[row]-1){
bridgePosition[bCount][0] = row; bridgePosition[bCount][1] = col;
bCount++;
//System.out.println("Bridge"+bCount+": "+row+"|"+col);
} else if (col>=islandCols[row-1]-1 || col>=islandCols[row+1]-1){
bridgePosition[bCount][0] = row; bridgePosition[bCount][1] = col;
//System.out.println("Bridge found: "+row+"|"+col);
bCount++;
}
break;
}
}
}
}
// moveMouse
// Computes the movement for the mouse
// set moveDebug to 'true' to display the mouse's moves
public void moveMouse(){
moveDebug = false;
int mouseMove = (int)(Math.random() * 4);
switch(mouseMove){
case 0: mousePosition[0][0]--; if (moveDebug == true) System.out.print("Move: "+mouseMove+"[UP] "); break;
case 1: mousePosition[0][0]++; if (moveDebug == true) System.out.print("Move: "+mouseMove+"[DOWN] "); break;
case 2: mousePosition[0][1]--; if (moveDebug == true) System.out.print("Move: "+mouseMove+"[LEFT] "); break;
case 3: mousePosition[0][1]++; if (moveDebug == true) System.out.print("Move: "+mouseMove+"[RIGHT] "); break;
}
if (moveDebug == true) System.out.println(" Location:|"+mousePosition[0][0]+"|"+mousePosition[0][1]+"|");
}
// runMouseIsland
// Displays the outcome of one trial of the current mouseIsland
public void runMouseIsland() throws Exception{
islandIntArray = new int [islandRows][maxValue(islandCols)];
mousePosition[0][0] = mousePosition [1][0]; mousePosition[0][1] = mousePosition [1][1];
for (int count=0;count<100;count++){
moveMouse();
if (mousePosition[0][0] == bridgePosition[0][0] && mousePosition[0][1] == bridgePosition[0][1] || mousePosition[0][0] == bridgePosition[1][0] && mousePosition[0][1] == bridgePosition[1][1] ){
System.out.println("The mouse has escaped using the bridge at: "+mousePosition[0][0]+"|"+mousePosition[0][1]);
islandIntArray[mousePosition[0][0]][mousePosition[0][1]]++;
mouseEscaped++;
break;
} else
if (islandCharArray[mousePosition[0][0]][mousePosition[0][1]] == '#') {
System.out.println("OUCH! The Mouse fell into the water and died at: "+mousePosition[0][0]+"|"+mousePosition[0][1]);
islandIntArray[mousePosition[0][0]][mousePosition[0][1]]++;
mouseDrowned++;
break;
}
islandIntArray[mousePosition[0][0]][mousePosition[0][1]]++;
if (count == 99){
System.out.println("The mouse withered away (died) at: "+mousePosition[0][0]+"|"+mousePosition[0][1]);
mouseStarved++;
}
}
drawIntIsland();
runCount++;
}
}

How do I check if a class' return of a method equals null?

In my program, I have a while loop that will display a list of shops and asks for an input, which corresponds with the shop ID. If the user enters an integer outside the array of shops, created with a Shop class, it will exit the loop and continue. Inside this loop is another while loop which calls the sellItem method of my Shop class below:
public Item sellItem()
{
displayItems();
int indexID = Shop.getInput();
if (indexID <= -1 || indexID >= wares.length)
{
System.out.println("Null"); // Testing purposes
return null;
}
else
{
return wares[indexID];
}
}
private void displayItems()
{
System.out.println("Name\t\t\t\tWeight\t\t\t\tPrice");
System.out.println("0. Return to Shops");
for(int i = 0; i < wares.length; i++)
{
System.out.print(i + 1 + ". ");
System.out.println(wares[i].getName() + "\t\t\t\t" + wares[i].getWeight() + "\t\t\t\t" + wares[i].getPrice());
}
}
private static int getInput()
{
Scanner scanInput = new Scanner(System.in);
int itemID = scanInput.nextInt();
int indexID = itemID - 1;
return indexID;
}
The while loop in my main class method is as follows:
boolean exitAllShops = true;
while(exitAllShops)
{
System.out.println("Where would you like to go?\nEnter the number which corresponds with the shop.\n1. Pete's Produce\n2. Moore's Meats\n3. Howards Hunting\n4. Foster's Farming\n5. Leighton's Liquor\n6. Carter's Clothing\n7. Hill's Household Products\n8. Lewis' Livery, Animals, and Wagon supplies\n9. Dr. Miller's Medicine\n10. Leave Shops (YOU WILL NOT BE ABLE TO RETURN)");
int shopInput = scan.nextInt();
if(shopInput >= 1 && shopInput <= allShops.length)
{
boolean leaveShop = true;
while(leaveShop)
{
allShops[shopInput - 1].sellItem();
if(allShops == null)
{
System.out.println("still null"); // Testing purposes
leaveShop = false;
}
}
}
else
{
System.out.println("Are you sure you want to leave?\n1. Yes\n2. No");
int confirm = scan.nextInt();
if(confirm == 1)
{
exitAllShops = false;
}
}
The problem is here:
boolean leaveShop = true;
while(leaveShop)
{
allShops[shopInput - 1].sellItem();
if(allShops == null)
{
System.out.println("still null"); // Testing purposes
leaveShop = false;
}
}
No matter what I do, I can't get "still null" to print to confirm that I'm correctly calling the return statement of the method sellItem of the class Shop. What am I doing wrong?
After calling allShops[...].sellItem(), allShops is still a valid array reference -- there's no way it could be null! You probably want to test the return value from sellItem:
if(allShops[shopInput-1].sellItem() == null)

Categories