Java. Array, save previous values - java

Cant figure out how to do this thing. I need to store and count number of "jumps" and direction of "jump" in array.
Console has to display something like this:
: Jump 1, direction Left
: Jump 2, direction Right
In my code below, when I print array elements, int jump always equals to 0;
I tried many variations, sometimes I got (for example):
jump();
jump();
jump();
jump();
And it prints: {0,0,0,4} , instead of {1,2,3,4};
public class Jump {
int jump;
String direction;
Jump[] jumpArray = new Jump[100];
int storeJump;
String storeDirection;
public void jump() {
jump++;
if (jump > 50) {
System.out.println("need a rest");
return;
} else {
for (int i = 0; i < jumpArray.length; i++) {
jumpArray[i] = new Jump();
}
}
jumpArray[jump].storeJump = jump;
jumpArray[jump].storeDirection = direction;
}
public static void main(String[] args) {
Jump jumper = new Jump();
jumper.jump();
jumper.jump();
for (int i = 0; i < jumper.jump; i++) {
System.out.println(jumper.jumpArray[i].jump);
}
}
}

I think the code below will solve your problem, but I think You should improve your code.
int jump;
String direction;
Jump[] jumpArray = new Jump[100];
int storeJump;
String storeDirection;
public void jumping() {
jump++;
if (jump > 50) {
System.out.println("need a rest");
return;
} else {
jumpArray[jump] = new Jump();
}
jumpArray[jump].storeJump = jump;
jumpArray[jump].storeDirection = direction;
}
public static void main(String[] args) {
Jump jumper = new Jump();
jumper.jumping();
jumper.jumping();
Set<Jump> mySet = new HashSet<Jump>(Arrays.asList(jumper.jumpArray));
for (int i = 1; i < mySet.size(); i++) {
System.out.println(jumper.jumpArray[i].storeJump);
}
}

I think it would make more sense to move the jumpArray into main():
public class Jump {
String direction;
//int storeJump; Not sure what this is for
//String storeDirection; Or this
#Override
public String toString() {
return direction;
}
// Static function that creates an initializes a Jump object
public static Jump jump(String direction) {
Jump jump = new Jump();
jump.direction = direction;
return jump;
}
public static void main (String[] args)
{
Jump[] jumpArray = new Jump[100];
int numJumps = 0;
// A list of directions for testing
String [] path = new String[]{"north", "south", "east", "west"};
// Create a bunch of jumps
for (String dir : path) {
if (numJumps > 50) {
System.out.println("need a rest");
break;
}
// Create a new jump and add to the array
jumpArray[numJumps++] = Jump.jump(dir);
}
// Print the jumps
for (int i = 0; i < numJumps; i++) {
System.out.println(i + " " + jumpArray[i]);
}
}
}

Related

Simple prisoner's dilemma genetic algorithm

I have used an existing genetic algorithm from
here
and reworked it I but don't know what I'm doing wrong
This is the error that I get
Exception in thread "main" java.lang.NullPointerException at
simpleGa.Algorithm.crossover(Algorithm.java:69) at
simpleGa.Algorithm.evolvePopulation(Algorithm.java:34) at
simpleGa.GAprisonerdilemma.main(GAprisonerdilemma.java:41)
I can't figure out exactly where the mistake is. Read a lot about NullPointerException but couldn't figure it out
package simpleGa;
public class Population {
public static Individual[] individuals;
/*
* Constructors
*/
// Create a population
public Population(int populationSize, boolean initialise) {
individuals = new Individual[populationSize];
// Initialise population
if (initialise) {
// Loop and create individuals
for (int i = 0; i < size(); i++) {
Individual newIndividual = new Individual();
newIndividual.generateIndividual();
saveIndividual(i, newIndividual);
}
for(int i=0;i<size();i++)
{
if(i%2==1){Individual individual1=individuals[i-1];
Individual individual2=individuals[i];
if(individuals[i-1].getGene(i-1)==0 && individuals[i].getGene(i)==0){
individuals[i-1].fitness=individual1.fitness+1;
individuals[i].fitness=individual2.fitness+1;
}
if(individuals[i-1].getGene(i-1)==1 && individuals[i].getGene(i)==1){
individuals[i-1].fitness=individual1.fitness+2;
individuals[i].fitness=individual2.fitness+2;
}
if(individuals[i-1].getGene(i-1)==0 && individuals[i].getGene(i)==1){
individuals[i-1].fitness=individual1.fitness+3;
individuals[i].fitness=individual2.fitness+0;
}
if(individuals[i-1].getGene(i-1)==1 && individuals[i].getGene(i)==0){
individuals[i-1].fitness=individual1.fitness+0;
individuals[i].fitness=individual2.fitness+3;
}
}}}
}
/* Getters */
public Individual getIndividual(int index) {
return individuals[index];
}
public Individual getFittest() {
Individual fittest = individuals[0];
// Loop through individuals to find fittest
for (int i = 1; i < size(); i++) {
if (fittest.getFitness() <= getIndividual(i).getFitness()) {
fittest = getIndividual(i);
}
}
return fittest;
}
/* Public methods */
// Get population size
public int size() {
return individuals.length;
}
// Save individual
public void saveIndividual(int index, Individual indiv) {
individuals[index] = indiv;
}
}
package simpleGa;
public class Individual {
static int defaultGeneLength = 1000;
private long[] genes =new long [defaultGeneLength];
// Cache
public static int fitness = 0;
// Create a random individual
public void generateIndividual() {
for (int i = 0; i < size(); i++) {
long gene = Math.round(Math.random());
genes[i] = gene;
}
}
/* Getters and setters */
// Use this if you want to create individuals with different gene lengths
public static void setDefaultGeneLength(int length) {
defaultGeneLength = length;
}
public long getGene(int i) {
return genes[i];
}
public void setGene(int index, long value) {
genes[index] = value;
fitness = 0;
}
/* Public methods */
public int size() {
return genes.length;
}
public static int getFitness() {
return fitness;
}
public void setFitness(int i) {
fitness=i;
}
#Override
public String toString() {
String geneString = "";
for (int i = 0; i < size(); i++) {
geneString += getGene(i);
}
return geneString;
}
}
package simpleGa;
public class Algorithm {
/* GA parameters */
private static final double uniformRate = 0.5;
private static final double mutationRate = 0.015;
private static final int tournamentSize = 5;
private static final boolean elitism = true;
/* Public methods */
// Evolve a population
public static Population evolvePopulation(Population pop) {
Population newPopulation = new Population(pop.size(), false);
// Keep our best individual
if (elitism) {
newPopulation.saveIndividual(0, pop.getFittest());
}
// Crossover population
int elitismOffset;
if (elitism) {
elitismOffset = 1;
} else {
elitismOffset = 0;
}
// Loop over the population size and create new individuals with
// crossover
for (int i = elitismOffset; i < pop.size(); i++) {
Individual indiv1 = tournamentSelection(pop);
Individual indiv2 = tournamentSelection(pop);
Individual newIndiv = crossover(indiv1, indiv2);
newPopulation.saveIndividual(i, newIndiv);
}
// Mutate population
for (int i = elitismOffset; i < newPopulation.size(); i++) {
mutate(newPopulation.getIndividual(i));
}
for(int i=0;i<pop.size();i++)
{for(int j=0;j<pop.getIndividual(i).size();j++)
{if(i%2==1){Individual individual1=Population.individuals[i-1];
Individual individual2=Population.individuals[i];
if(Population.individuals[i-1].getGene(i-1)==0 && Population.individuals[i].getGene(i)==0){
Population.individuals[i-1].fitness=individual1.fitness+1;
Population.individuals[i].fitness=individual2.fitness+1;
}
if(Population.individuals[i-1].getGene(i-1)==1 && Population.individuals[i].getGene(i)==1){
Population.individuals[i-1].fitness=individual1.fitness+2;
Population.individuals[i].fitness=individual2.fitness+2;
}
if(Population.individuals[i-1].getGene(i-1)==0 && Population.individuals[i].getGene(i)==1){
Population.individuals[i-1].fitness=individual1.fitness+3;
Population.individuals[i].fitness=individual2.fitness+0;
}
if(Population.individuals[i-1].getGene(i-1)==1 && Population.individuals[i].getGene(i)==0){
Population.individuals[i-1].fitness=individual1.fitness+0;
Population.individuals[i].fitness=individual2.fitness+3;
} }}}``
return newPopulation;
}
// Crossover individuals
private static Individual crossover(Individual indiv1, Individual indiv2) {
Individual newSol = new Individual();
// Loop through genes
for (int i = 0; i < indiv1.size(); i++) {
// Crossover
if (Math.random() <= uniformRate) {
newSol.setGene(i, indiv1.getGene(i));
} else {
newSol.setGene(i, indiv2.getGene(i));
}
}
return newSol;
}
// Mutate an individual
private static void mutate(Individual indiv) {
// Loop through genes
for (int i = 0; i < indiv.size(); i++) {
if (Math.random() <= mutationRate) {
// Create random gene
long gene = Math.round(Math.random());
indiv.setGene(i, gene);
}
}
}
// Select individuals for crossover
private static Individual tournamentSelection(Population pop) {
// Create a tournament population
Population tournament = new Population(tournamentSize, false);
// For each place in the tournament get a random individual
for (int i = 0; i < tournamentSize; i++) {
int randomId = (int) (Math.random() * pop.size());
tournament.saveIndividual(i, pop.getIndividual(randomId));
}
// Get the fittest
Individual fittest = tournament.getFittest();
return fittest;
}
package simpleGa;
public class FitnessCalc {
/* Public methods */
// Set a candidate solution as a byte array
// To make it easier we can use this method to set our candidate solution
// with string of 0s and 1s
// Calculate inidividuals fittness by comparing it to our candidate solution
static int getFitness(Individual individual) {
int fitness = 0;
// Loop through our individuals genes and compare them to our cadidates
fitness=Individual.fitness;
return fitness;
}
}
// Get optimum fitness
}
package simpleGa;
import java.util.Scanner;
public class GAprisonerdilemma {
public static void main(String[] args) {
// Set a candidate solution
Scanner keyboard = new Scanner(System.in);
System.out.println("Input number of games!");
int k = keyboard.nextInt();
Individual.setDefaultGeneLength(k);
// Create an initial population
System.out.println("Input number of individuals in the population!");
int p = keyboard.nextInt();
Population myPop = new Population(p, true);
System.out.println("Input acceptable number of generations!");
int l = keyboard.nextInt();
// Evolve our population until we reach an optimum solution
int generationCount = 0;
int j=l+1;
System.out.println("Input requiered fitness value !");
int f = keyboard.nextInt();
int h=0;
// Evolve our population until we reach an optimum solution
for(int i=0;i<j;i++)
{
if(i==0){}
else{
if(myPop.getFittest().getFitness()>=f){if(h==0){h++;}
else{ System.out.println("Solution found!");
System.out.println("Generation: " + generationCount);
System.out.println( "Fitness(Points): " + myPop.getFittest().getFitness());
break;}
}else {myPop = Algorithm.evolvePopulation(myPop);
generationCount++;
System.out.println("Generation: " + generationCount + " Fittest: " + myPop.getFittest().getFitness());
}
if(i==j-1){ if(myPop.getFittest().getFitness()>=f)System.out.println("Solution found !");
else System.out.println("Solution not found closest solution is!");
System.out.println("Generation: " + generationCount);
System.out.println( " Fitness(Points): " + myPop.getFittest().getFitness());}
}
}
System.out.println("0 for betrays in that turn 1 for cooperates!");
System.out.println("Turns:");
System.out.println(myPop.getFittest());
}
}

How to load/create a level/room from a text file in java?

Basically each room has a size of 10 by 10, the "W" represents the Walls, and the blank spaces -" " represent the Floor, and the numbers are Doors.I figured the best way to create the room is to create a method that receives a file and reads it and put its "information" into a String[10][10], and then create another method(or just do it in my Main) that receives the String[10][10] created and creates the room(adds the images to the room), but i am having some difficulties reading the file so if you guys could help me with that part i would be thankful.
Here is the type of text files from which i want to create my room:
WWWW0WWWWW
W W
W W
W W
W W
W WW
W WW
W WW
W W1
WWWWWWWWWW
Here are the Door, Wall and Floor classes:
public class Door implements ImageTile {
private Position position;
public Door(Position position) {
this.position = position;
}
#Override
public String getName() {
return "Door";
}
#Override
public Position getPosition() {
return position;
}
}
public class Floor implements ImageTile {
private Position position;
public Floor(Position position) {
this.position = position;
}
#Override
public String getName() {
return "Floor";
}
#Override
public Position getPosition() {
return position;
}
}
public class Wall implements ImageTile {
private Position position;
public Wall(Position position) {
this.position = position;
}
#Override
public String getName() {
return "Wall";
}
#Override
public Position getPosition() {
return position;
}
}
And this is my method for adding images to my frame:
public void newImages(final List<ImageTile> newImages) {
if (newImages == null)
return;
if (newImages.size() == 0)
return;
for (ImageTile i : newImages) {
if (!imageDB.containsKey(i.getName())) {
throw new IllegalArgumentException("No such image in DB " + i.getName());
}
}
images.addAll(newImages);
frame.repaint();
}
If you guys could help me i would appreciate it very much, thanks guys.Her is what i have now:
public class Room {
private String[][]room;
public Room(){
room = new String[10][10]; }
public static Room fromFile(File file){
if(file.exists()){
Scanner sc = null;
Room room = new Room();
try {
sc = new Scanner(file);
while(sc.hasNextLine()){
if(sc.nextLine().startsWith("#"))
sc.nextLine();
else{
String[] s0 = sc.nextLine().split("");
//Here is where my trouble is, i dont know how to add the content of this String s0 to the String s
if(s0.length==10){
for(int x = 0; x < 10; x++){
for(int y = 0; y < 10; y++){
String[x][y] s= String[x] s0;
}
}
} catch (FileNotFoundException e) {
System.out.println("Ficheiro "+file.getAbsolutePath()+
" não existe. "); }
finally{
if(sc!=null)sc.close();
}
}
else
System.out.println("Ficheiro "+file.getAbsolutePath()+
" não existe. ");
return null;
}
Each call to sc.nextLine() is reading another line from your file. You need to save the line into a temporary variable, and then refer to that temporary.
Maintain a counter of lines you've processed, so you can fill in the appropriate line in your s[][] matrix.
You only need to allocate storage for the 10 rows, since splitting the line you read in will result in an array of strings (the columns in one row) being allocated for you.
int row = 0;
String[][] s = new String[10][];
while(sc.hasNextLine() && i < 10) {
String line = sc.nextLine();
if( !line.startsWith("#")) {
String[] s0 = sc.line.split("");
s[row] = s0;
row++;
}
}
BTW, Use String[][] is overkill; since each string will only hold one character. Perhaps you could consider using char[][]. And line.toCharArray() would split the line into a char[] for you.
EDIT: (Due to edit of your question's code)
Instead of:
if(s0.length==10){
for(int x = 0; x < 10; x++){
for(int y = 0; y < 10; y++){
String[x][y] s= String[x] s0;
}
}
}
you want:
if(s0.length==10){
for(int y = 0; y < 10; y++){
s[row][y] = s0[y];
}
row++;
}
With row being the row counter in my above code.

Trying to Debug very glitchy blackjack game in java

First, thanks for reading this, I'm going to start by posting all code relevant to the program which you can skim or completely skip over for now.
Try to ignore all my sarcastic comments throughout the code btw they aren't directed at stack overflow :P
BlackJack file:
import java.util.Scanner;
import java.util.InputMismatchException;
public class BlackJack { //i should probably put a betting thing somewhere.....
//also should probably add a thing that tells them one of the dealers cards
//should also put something that stops 2 players from having the same name
static Scanner input = new Scanner(System.in); //honestly have no idea if i can put this here but it seems to work. keyword; seems
//good lucking counting cards with all this shuffling lol
public void absolutelyNothing() { //maybe put a betting method here instead of a method that does nothing???
//Do NOT Delete This Method!
}
public static void displayHands(Hand[] hands, String[] playerNames, int players) {
for (int i = 1; i < players; i++) {
display(hands, playerNames, i);
}
displayDealer(hands);
}
public static void display(Hand[] hands, String[] playerNames, int i) {
System.out.println(playerNames[i] + " has " + hands[i]);
}
public static void displayDealer(Hand[] hands) {
System.out.println("Dealer has " + hands[0].dealerDisplay());
}
public static boolean win(Hand[] hands, int i) {
int value = worth(hands[i]);
int dealer = worth(hands[0]);
if (value == -1) {
return false;
}
if (value > dealer) {
return true;
}
return false;
}
public static void winners(Hand[] hands, String[] playerNames) {
for (int i = 1; i < hands.length; i++) {
if (win(hands, i) == true) {
System.out.println(playerNames[i] + " beat the dealer");
}
else {
System.out.println(playerNames[i] + " lost to the dealer");
}
}
}
public static int worth(Hand hand) {
int sum = 0;
int aces = 0;
for (int i = 0; i < hand.howManyCards(); i++) {
Card card = hand.getCard(i);
int value;
if (card.getNumber() == -10) {
aces++;
value = 11;
}
else {
value = card.getNumber();
}
sum+= value;
}
for (int i = 0; aces > i; i++) {
if (sum >= 22) {
sum = sum - 10;
}
}
if (sum >= 22) {
return -1;
}
return sum;
}
public static void dealerTurn(Deck deck, Hand[] hands) {
int worth = worth(hands[0]);
while (worth < 16) {
dealCard(deck, hands, 0);
}
}
public static void playTurn(Deck deck, Hand[] hands, int i, String[] playerNames) {
// System.out.println(playerNames[i] + " hit?" + " Your hand is worth " + worth(hands[i]) );
boolean hit;
displayHands(hands, playerNames, hands.length);
while (true) {
if (worth(hands[i]) == -1) {
System.out.println("Bust");
break;
}
System.out.println(playerNames[i] + " hit?" + " Your hand is worth " + worth(hands[i]) );
try {
hit = input.nextBoolean();
}
catch (InputMismatchException exception) {
System.out.println("Please enter \"true\" or \"false\"");
continue; //pretty sure this continue is causing the glitch where if you don't enter a boolean it goes insane
}
if (hit == true) {
dealCard(deck, hands, i);
}
else {
break;
}
}
}
public static void everyoneGo(Deck deck, Hand[] hands, int players, String[] playerNames) {
for (int j = 1; j < players + 1; j++) { //players go
playTurn(deck, hands, j, playerNames);
}
dealerTurn(deck, hands);
}
public static Deck newHand(Deck deck) {
Deck newDeck = new Deck();
return newDeck;
}
public static void dealCard(Deck deck, Hand[] hands, int i) {
deck.shuffleDeck();
//goodluck counting cards
hands[i].addCard(deck.getCard(0));
deck.removeCard(0);
}
public static void giveNextCard(Hand[] hands, Deck deck, int i) {
hands[i].addCard(deck.getCard(0));
deck.removeCard(0);
}
public static Hand[] firstTwoCards(int players, String[] playerNames, Deck deck) { //gives dealer cards first an I'm too lazy to fix
deck.shuffleDeck();
//seriously good luck
Hand[] hands = new Hand[players + 1]; //dealer is hands[0]
for (int i = 0; i < players + 1; i++) {
hands[i] = new Hand(playerNames[i]);
}
for (int j = 0; j < 2; j++) {
for (int i = 0; i < players + 1; i++) {
giveNextCard(hands, deck, i);
}
}
return hands;
}
public static String[] getNames(int players) {
System.out.println("What are the names of the players?");
String[] playerNames = new String[players + 1];
playerNames[0] = "Dealer";
for (int i = 1; i < players + 1; i++) {
playerNames[i] = input.next(); //something with this line the last time you use it
}
return playerNames;
}
public static int peoplePlaying() {
System.out.println("How many people are playing?");
int players = input.nextInt();
return players;
}
public static void main(String[] args) {
int players = peoplePlaying();
String[] playerNames = getNames(players);
Deck deck = new Deck();
Hand[] hands = firstTwoCards(players, playerNames, deck);
everyoneGo(deck, hands, players, playerNames);
winners(hands, playerNames);
}
}
//if you're smart you would have realized all this shuffling has absolutely no effect on counting cards lol now figure out why
Hand File:
public class Hand extends CardList {
public Hand(String label) {
super(label);
}
public void display() {
System.out.println(getLabel() + ": ");
for (int i = 0; i < size(); i++) {
System.out.println(getCard(i));
}
System.out.println();
}
}
Deck File:
public class Deck extends CardList {
public Deck(String label) {
super(label);
for (int suit = 0; suit <= 3; suit++) {
for (int rank = 1; rank <= 13; rank++) {
addCard(new Card(rank, suit));
}
}
}
}
Cardlist File:
import java.util.ArrayList;
import java.util.Random;
public class CardList {
public String name;
public ArrayList<Card> cards;
public CardList(String name) {
this.name = name;
this.cards = new ArrayList<Card>();
}
public String toString() {
String s = "";
for (int i = 0; i < cards.size(); i++) {
s = s + cards.get(i) + ", ";
}
return s;
}
public String dealerDisplay() {
return cards.get(0).toString();
}
public String getName() {
return name;
}
public Card getCard(int i) {
return cards.get(i);
}
public int howManyCards() {
return cards.size();
}
public void addCard(Card card) {
cards.add(card);
}
public void removeCard(int i) {
cards.remove(i);
}
public void swapCards(int i, int j) {
Card wait = cards.get(i);
cards.set(i, cards.get(j));
cards.set(j, wait);
}
public void shuffleDeck() {
for (int k = 0; k < 10; k++) { //not sure how well the algorithm works but if you do it 10 times it shouldn't matter how bad it is
for (int i = 0; i < howManyCards(); i++) {
int j = (int) (Math.random() * howManyCards());
swapCards(i, j);
}
}
}
}
and finally the card object:
public class Card {
int number;
int suit;
public static final String[] NUMBERS = {null, null, "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"};
public static final String[] SUITS = {"Diamonds", "Clubs", "Spades", "Hearts"};
public Card(int number, int suit) {
this.number = number;
this.suit = suit;
}
#Override
public String toString() {
return NUMBERS[number] + " of " + SUITS[suit];
}
public int getNumber() {
if (number == 14) { //used to tell if its an ace in blackjack file
return -10;
}
if (number < 11) {
return number;
}
else {
return 10;
}
}
}
Alright so hopefully you didn't kill yourself by attempting to read all of that and I realize my code style/organization could use some work.
Anyways their are a few things that are very weird with the program that I can't seem to figure out. Sometimes the program will run fine and you can play a full game with lots of players but other times it throws a bunch of exceptions.
basically if you bust (go over 21) the program throws this 100% of the time:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at CardList.getCard(CardList.java:31)
at BlackJack.dealCard(BlackJack.java:151)
at BlackJack.dealerTurn(BlackJack.java:93)
at BlackJack.everyoneGo(BlackJack.java:138)
at BlackJack.main(BlackJack.java:209)
btw if someone could explain what it means by exceptions at lines that don't exist such as 653 (the first message) that would be very helpful.
It also throws the same exception some of the time even if you don't bust which I'm assuming is the dealer busting as the dealer plays automatically obeying the regular casino rules for dealers.
If anyone can figure it out it would be greatly appreciated, thanks!

ArrayList replacing everything before when new element is added?

I'm attempting to add elements into an arraylist (also append an arraylist to the other), however it seems to rewrite everything else already present in that arraylist too - so I'm left with an arraylist filled with the last element added.
Here's the method concerned:
private static ArrayList<Move> checkX(int r, int c) {
ArrayList<Move> moves = new ArrayList<Move>();
if (jumps()) { // if jumps are found && this piece can jump
for (int i = 0; i <= 1; i+=2) {
if (Character.isLowerCase(board[r-1][c+i]) && board[r-2][c+2*i] == ' ') {
}
}
} else { // if no jumps are found then move normally
for (int i = -1; i <= 1; i+=2) {
try {
if (board[r-1][c+i] == ' ') {
Move tempMove = new Move(r, c);
tempMove.addDestination((r-1), (c+i));
moves.add(tempMove);
}
} catch (Exception e) {}
}
}
for (int i = 0; i < moves.size(); i++) {
System.out.println(moves.get(i).toString());
}
return moves;
}
Move class:
public class Move {
private static ArrayList<int[]> destinations;
// private static char[][] tmpboard;
public Move(int r, int c) {
destinations = new ArrayList<int[]>();
int[] initSquare = {r, c};
destinations.add(initSquare);
}
public void addDestination(int r, int c) {
int[] destinationSquare = {r, c};
destinations.add(destinationSquare);
}
public ArrayList<int[]> getMove() {
return destinations;
}
public String toString() {
String returnStr = "";
for (int i = 0; i < destinations.size(); i++) {
returnStr += Arrays.toString(destinations.get(i));
}
return returnStr;
}
}
Every time I attempt to print out everything stored in an instance of 'moves' it seems to only print out the last element added to the list n times.
private static ArrayList<int[]> destinations;
Here's your issue. Try removing the static modifier.
What static here means that the latest additions of destinations will affect all Move instances, which makes them identical.
It's possible you were thinking of final there instead, which would make more sense.

java text based world moving elements around

I have a project that i cannot for the life of me figure out the moving pattern, whether some object is in the same place as another, or how to interact with each project, here is the first class:
public class AnimalKingdom {
public static final int WORLD_ROWS = 4;
public static final int WORLD_COLUMNS = 4;
public static final int ROUNDS = 10;
public static void main(String[] args) {
Animal[] animals = new Animal[10];
animals[0] = new Worm(WORLD_ROWS, WORLD_COLUMNS);
animals[1] = new Worm(WORLD_ROWS, WORLD_COLUMNS);
animals[2] = new Worm(WORLD_ROWS, WORLD_COLUMNS);
animals[3] = new Worm(WORLD_ROWS, WORLD_COLUMNS);
animals[4] = new Bird(WORLD_ROWS, WORLD_COLUMNS);
animals[5] = new Bird(WORLD_ROWS, WORLD_COLUMNS);
animals[6] = new Bird(WORLD_ROWS, WORLD_COLUMNS);
animals[7] = new Bird(WORLD_ROWS, WORLD_COLUMNS);
animals[8] = new Wolf(WORLD_ROWS, WORLD_COLUMNS);
animals[9] = new Wolf(WORLD_ROWS, WORLD_COLUMNS);
for (int i = 1; i < ROUNDS; i++) {
showWorld(animals);
doEating(animals);
doMoving(animals);
}
}
public static void showWorld(Animal[] animals) {
System.out.println();
System.out.println("The World");
/* The world is made of rows and columns.
Each location must be big enough to list all the animals
(in case they all show up at that spot at once). So we print
the single character string for each animal, then later add in enough
blanks to ensure that the lines between locations are neatly
drawn. */
for (int r = 0; r < WORLD_ROWS; r++) {
for (int c = 0; c < WORLD_COLUMNS; c++) {
int localAnimals = 0;
for (int a = 0; a < animals.length; a++) {
if (animals[a] != null) { // as animals die, nulls will be left in the array
int ar = animals[a].getRow();
int ac = animals[a].getCol();
if (r == ar && c == ac) { // this animal is local to this location
localAnimals++;
System.out.print(animals[a]); // draw the animal
}
}
}
// create enough blanks to fill out the location
for (int i = 0; i < animals.length-localAnimals; i++) {
System.out.print(" ");
}
System.out.print("|");
}
System.out.println();
}
System.out.println();
}
public static void doEating(Animal[] animals) {
// This needs to be filled in
}
public static void doMoving(Animal[] animals) {
// This needs to be filled in
}
}
And here is the second part of my coding:
import java.util.Random;
public class Animal {
private Random rand = new Random();
private int worldWidth;
private int worldHeight;
private int row;
private int col;
public Animal(int worldHeight, int worldWidth) {
this.worldHeight = worldHeight;
this.worldWidth = worldWidth;
row = rand.nextInt(worldHeight);
col = rand.nextInt(worldWidth);
}
public boolean willEat(Animal anim) {
return false;
}
public void move() {
}
public int getRow() {
return row;
}
public int getCol() {
return col;
}
public void setRow(int r) {
row = r;
}
public void setCol(int c) {
col = c;
}
public String toString() {
return "";
}
public int getWorldWidth(){
return worldWidth;
}
public int getWorldHeight(){
return worldHeight;
}
public boolean isInSamePlaceAs(Animal other) {
return false; // code needs to be replaced
}
}
Each subclass is named Worm, Bird, and Wolf. Each subclass toString is represented in the form of one char. 'B' for Bird, '.' for Worm, and 'W' for Wolf. The worms can move left and right, remembering the direction they are going in and reverse if they hit a wall or end/beginning of array. The Bird moves diagonally in the world. The Wolf is allowed to move in any direction.
I just need help with starting to make movements in the doMoving(), help identify isInSamePlaceAs() and help doEating(). Birds eat worms, Wolves eat Birds, and worms do nothing.

Categories

Resources