My project requires me to make a game where two space ships move around on a game board. I'm not too sure on how to get my X and Y position values from my constructors to my method in my main program.
I got a bit of help from my professor and he said to pass the X and Y values into my print board method I tried to use ship1.XPos, ship1.YPos, ship2.XPos, ship2.YPos in my print board declaration but I got an error about VariableDeclaratiorId.
Here is my main as it is currently as is right now
Java
package ship;
import java.util.*;
public class ShipGame {
public static String[][] makeBoard() {
String[][] f = new String[6][22];
for (int i = 0; i < f.length; i++) {
for (int j = 0; j < f[i].length; j++) {
if (j % 2 == 0)
f[i][j] = "|";
else
f[i][j] = " ";
}
}
return f;
}
public static void printBoard(String[][] f, ship1.XPos, ship1.YPos, ship2.XPos, ship2.YPos) {
for (int i = 0; i < f.length; i++) {
for (int j = 0; j < f[i].length; j++) {
if(x == ship1.XPos && y == ship1.YPos){
System.out.print(ship1);
}
else if (x == ship2.XPos && y == ship2.YPos){
System.out.ptint(ship2);
}
else{
System.out.print(f[i][j]);
}
System.out.println();
}
}
}
public static void main(String[] args) {
int engine;
System.out.println("Welcome First Captian! What kind of ship would you like to create: ");
System.out.println("1. Battlecruiser");
System.out.println("2. Destroyer");
Scanner scan = new Scanner(System.in);
engine = scan.nextInt();
scan.nextLine();
String engineType;
if (engine == 1) {
engineType = "Battlecrusier";
}
else {
engineType = "Destroyer";
}
System.out.println("What would you like to name your vessel?");
String shipName1 = scan.nextLine();
Spaceship1 ship1 = new Spaceship1(shipName1, engineType);
System.out.println("Welcome Second Captian! What kind of ship would you like to create: ");
System.out.println("1. Battlecruiser");
System.out.println("2. Destroyer");
engine = scan.nextInt();
scan.nextLine();
if (engine == 1) {
engineType = "Battlecrusier";
}
else {
engineType = "Destroyer";
}
System.out.println("What would you like to name your vessel?");
String shipName2 = scan.nextLine();
Spaceship2 ship2 = new Spaceship2(shipName2, engineType);
String[][] f = makeBoard();
int count = 0;
printBoard(f);
boolean gaming = true;
while (gaming) {
if (count % 2 == 0) {
ship1.movement1(f);
}
else {
ship2.movement2(f);
}
count++;
printBoard(f, ship1.XPos, ship1.YPos, ship2.XPos, ship2.YPos );
gaming = false;
}
}
}
Here is my Spaceship1 constructor. It is the same as my Spaceship2 constructor so there's no need to add it
Java
package ship;
import java.util.Random;
import java.util.Scanner;
public class Spaceship1 extends ship {
private String ship1;
public Spaceship1(String shipName, String engineType) {
super(shipName, engineType);
double maxSpeed = Math.random() * 2 + 1;
int shipHealth = (int) (Math.random() * 100 + 50);
int attackPower = (int) (Math.random() * 20 + 5);
Random rand = new Random();
int newXPos = rand.nextInt(9);
int newYPos = rand.nextInt(9);
setShipHealth(shipHealth);
setMaxSpeed(maxSpeed);
setAttackPower(attackPower);
setXPos(newXPos);
setYPos(newYPos);
}
public void movement1(String[][] f) {
System.out.println("W Move Up");
System.out.println("S Move Down");
System.out.println("A Move Left");
System.out.println("D Move Right");
Scanner scan = new Scanner(System.in);
String move = scan.nextLine();
int standX = getXPos();
int standY = getYPos();
double standS = getMaxSpeed();
if(move == "W")
{
standY += standS;
setYPos(standY);
}
else if(move == "S")
{
standY += standS;
setYPos(standY);
}
else if(move == "A")
{
standY += standS;
setYPos(standY);
}
else if(move == "D")
{
standY += standS;
setYPos(standY);
}
}
}
I expect there to be the words Ship1 and Ship2 on any space on my game board that is declared as 6x22.
When you define a method, you need to define the arguments it accepts using their types and names that the method will use to refer to those arguments. For example, your code:
public static void printBoard(String[][] f, ship1.XPos, ship1.YPos, ship2.XPos, ship2.YPos)
should actually be written like so:
public static void printBoard(String[][] f, int ship1Xpos, int ship1Ypos, int ship2Xpos, int ship2Ypos)
The reason your code doesn't work is because you're trying to define the method using the values you want to pass into it (e.g., ship1.XPos). When you want to call the method, then you can give it the values that you want it to use, like so:
printBoard(f, ship1.XPos, ship1.YPos, ship2.XPos, ship2.YPos);
Keep in mind that you also have the following line of code which won't work because you're not passing a value for all of the arguments it expects:
printBoard(f);
Related
I need to make a counter array for a Rock Paper Scissors game but can not figure out how to make user input call the enum, and i need to make the moves for the game a counter for them to be used and compared to.
This is my enum
public enum Moves {
Rock(1),
Paper(2),
Scissors(3),
Lizard(4),
Spock(5), ;
private int countOf = 0;
private int moveVal;
private ArrayList<Moves> movesList = new ArrayList<>();
Moves(int moveVal) {
}
public int getmoveVal() {
return moveVal;
}
public int getCountOf() {
for(Moves moveList : Moves.values()) {
countOf++;
}
return countOf;
}
And this is my class that would call it
public static void main(String[] args) {
RockPaperScissorGame rsg = new RockPaperScissorGame(3);
Moves move[] = Moves.values();
int playerMove = 0;
for(int i = 0; i < move.length; i++) {
}
boolean continueGame = true;
#SuppressWarnings("resource")
Scanner keyboard = new Scanner(System.in);
while(continueGame)
{
System.out.println(rsg.moveChoices());
System.out.println("Enter Move:(1,2,3,4 or 5):");
playerMove = keyboard.nextInt();
rsg.playRound(move);
System.out.printf("AI %s!%n", rsg.getAIOutcome().toString());
System.out.printf("Player %s!%n", rsg.getPlayerOutcome().toString());
System.out.println(rsg.moveOutcome());
System.out.println(rsg.currentScore());
if(rsg.isGameOver())
{
System.out.println(rsg.currentWinTotal());
System.out.println("Do you want to Play Again(1 - Yes , 2 - No):");
int answer = keyboard.nextInt();
if(answer == 2)
{
continueGame = false;
}
else
{
rsg.reset();
}
}
}
You can iterate through values to find a Move matching that moveVal:
public Move fromMoveVal(int moveVal) {
for (Move m : Move.values()) if (m.moveVal == moveVal) return m;
return null;
}
The purpose of the program is to let the user input 5 numbers and select which game they would like to compare them to (lotto/lottoplus1/lottoplus2) with each having a unique set of 5 numbers, then to be stored in an arraylist.
The national lottery run three draws on each night: Lotto, Lotto plus one and Lotto plus 2.
generate numbers for each of these draws.
When a user enters a line of numbers they should also enter either:"lotto", "plus1", or "plus2" to specify which of the draws their numbers should be compared to.
This value should then be assigned to that specific line of numbers and the numbers on that line should be compared against each set of Lotto numbers as required.
Heres my problem! When I input my five numbers then lets say 'plus1' to assign the comparison of those numbers to lotteryPlusOne it crashes and outputs this message:
Exception in thread "main" java.lang.NullPointerException at lottoapp.lottoCounter.compareNums(lottoCounter.java:136) at lottoapp.LottoApp.main(LottoApp.java:61) C:\Users\x15587907\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1 BUILD FAILED (total time: 15 seconds)
Below is line 136 it is in the Instantiable class in the public void compareNums() method
l = madeUpArrayList.get(i); <-----
Main App
package lottoapp;
import javax.swing.JOptionPane;
import java.util.ArrayList;
import java.util.Arrays;
public class LottoApp {
public static void main(String[] args) {
//declare vars/objects/arrays
int[] lottery = new int[5]; //5 Winning numbers
int[] lotteryPlus1 = new int[5]; //5 Winning LP1 numbers
int[] lotteryPlus2 = new int[5]; //5 Winning LP2 numbers
String gameType;
int number1;
int number2;
int number3;
int number4;
int number5;
//array list called madeUpArrayList
ArrayList<lottoCounter> madeUpArrayList = new ArrayList();
//object declare and create
lottoCounter myCount = new lottoCounter();
//winNums/getLottery need to be initialised at top of program
myCount.winNums();
lottery = myCount.getLottery();
lotteryPlus1 = myCount.getLotteryPlus1();
lotteryPlus2 = myCount.getLotteryPlus2();
//Displays winning numbers (Testing Purposes)
System.out.println(Arrays.toString(lottery));
System.out.println(Arrays.toString(lotteryPlus1));
System.out.println(Arrays.toString(lotteryPlus2));
//Array List
for (int i = 0; i < 1; i++) {
lottoCounter l = new lottoCounter();
number1 = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter number 1 "));
number2 = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter number 2 "));
number3 = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter number 3 "));
number4 = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter number 4 "));
number5 = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter number 5 "));
gameType = JOptionPane.showInputDialog(null, "Select a game type for comparison ... lotto/plus1/plus2");
l.setNumber1(number1);
l.setNumber2(number2);
l.setNumber3(number3);
l.setNumber4(number4);
l.setNumber5(number5);
l.setGameType(gameType);
madeUpArrayList.add(l);
}
//Comparison
myCount.compareNums();
//Output Lotto,Lotto Plus One and Lotto plus Two correct guesses
JOptionPane.showMessageDialog(null, "Guesses correct for Regular Lottery correct is " + myCount.getCorrectLotto());
JOptionPane.showMessageDialog(null, "Guesses correct for Lottery Plus One is " + myCount.getCorrectPlusOne());
JOptionPane.showMessageDialog(null, "Guesses correct for Lottery Plus Two is " + myCount.getCorrectPlusTwo());
}
}
Instantiable Class
package lottoapp;
import java.util.ArrayList;
public class lottoCounter {
//Variables/Constants/data members
private int correctLotto;
private int correctPlusOne;
private int correctPlusTwo;
private int[] lottery = new int[5];
private int[] lotteryPlus1 = new int[5];
private int[] lotteryPlus2 = new int[5];
private int number1;
private int number2;
private int number3;
private int number4;
private int number5;
private String gameType;
private ArrayList<lottoCounter> madeUpArrayList;
//Constructor
lottoCounter() {
correctLotto = 0;
correctPlusOne = 0;
correctPlusTwo = 0;
number1 = 0;
number2 = 0;
number3 = 0;
number4 = 0;
number5 = 0;
gameType = " ";
}
//setters
public void setCorrectLotto(int correctLotto) {
this.correctLotto = correctLotto;
}
public void setCorrectPlusOne(int correctPlusOne) {
this.correctPlusOne = correctPlusOne;
}
public void setCorrectPlusTwo(int correctPlusTwo) {
this.correctPlusTwo = correctPlusTwo;
}
public void setLottery(int[] lottery) {
this.lottery = lottery;
}
public void setLotteryPlus1(int[] lotteryPlus1) {
this.lotteryPlus1 = lotteryPlus1;
}
public void setLotteryPlus2(int[] lotteryPlus2) {
this.lotteryPlus1 = lotteryPlus2;
}
public void setNumber1(int number1) {
this.number1 = number1;
}
public void setNumber2(int number2) {
this.number2 = number2;
}
public void setNumber3(int number3) {
this.number3 = number3;
}
public void setNumber4(int number4) {
this.number4 = number4;
}
public void setNumber5(int number5) {
this.number5 = number5;
}
public void setGameType(String gameType) {
this.gameType = gameType;
}
public lottoCounter(ArrayList<lottoCounter> madeUpArrayList) {
this.madeUpArrayList = madeUpArrayList;
}
//COMPUTE
//Lottery Generator | random num generator (1-40)Lottery
public void winNums() {
for (int i = 0; i < lottery.length; i++) {//Generating 1 to 40 numbers
lottery[i] = (int) Math.floor(1 + Math.random() * 40);//Using Math.random
for (int j = 0; j < i; j++) {
if (lottery[i] == lottery[j]) {
i--;
}
}
}
//Lottery plus 1 generator
for (int i = 0; i < lotteryPlus1.length; i++) {//Generating 1 to 40 numbers
lotteryPlus1[i] = (int) Math.floor(1 + Math.random() * 40);//Using Math.random
for (int j = 0; j < i; j++) {
if (lotteryPlus1[i] == lotteryPlus1[j]) {
i--;
}
}
}
//Lottery plus 2 generator
for (int i = 0; i < lotteryPlus2.length; i++) {//Generating 1 to 40 numbers
lotteryPlus2[i] = (int) Math.floor(1 + Math.random() * 40);//Using Math.random
for (int j = 0; j < i; j++) {
if (lotteryPlus2[i] == lotteryPlus2[j]) {
i--;
}
}
}
}
//Counter for Lottery/LotteryPlusOne/LotteryPlusTwo (COMPARISON)
public void compareNums() {
for (int i = 0; i < 1; i++) {
for (int j = 0; j < 5; j++) {
lottoCounter l;
l = madeUpArrayList.get(i);
if (l.getGameType().equals("lotto")) {
if (lottery[j] == l.getNumber1() || lottery[j] == l.getNumber2() || lottery[j] == l.getNumber3() || lottery[j] == l.getNumber4() || lottery[j] == l.getNumber5()) {
correctLotto++;
}
}
if (l.getGameType().equals("plus1")) {
if (lotteryPlus1[j] == l.getNumber1() || lotteryPlus1[j] == l.getNumber2() || lotteryPlus1[j] == l.getNumber3() || lotteryPlus1[j] == l.getNumber4() || lotteryPlus1[j] == l.getNumber5()) {
correctPlusOne++;
}
}
if (l.getGameType().equals("plus2")) {
if (lotteryPlus2[j] == l.getNumber1() || lotteryPlus2[j] == l.getNumber2() || lotteryPlus2[j] == l.getNumber3() || lotteryPlus2[j] == l.getNumber4() || lotteryPlus2[j] == l.getNumber5()) {
correctPlusTwo++;
}
}
}
}
}
//getters (return values to App Class)
public int getCorrectLotto() {
return correctLotto;
}
public int getCorrectPlusOne() {
return correctPlusOne;
}
public int getCorrectPlusTwo() {
return correctPlusTwo;
}
public int[] getLottery() {
return lottery;
}
public int[] getLotteryPlus1() {
return lotteryPlus1;
}
public int[] getLotteryPlus2() {
return lotteryPlus2;
}
public int getNumber1() {
return number1;
}
public int getNumber2() {
return number2;
}
public int getNumber3() {
return number3;
}
public int getNumber4() {
return number4;
}
public int getNumber5() {
return number5;
}
public String getGameType() {
return gameType;
}
public ArrayList<lottoCounter> getMadeUpArrayList() {
return madeUpArrayList;
}
}
I am not sure about anyone else but it would be nice to have more info, like the data in the arrays: lottery, lotteryPlus1 and madeUpArrayList ect. Just to make sure that they actually have any data in them because according to your Exception you have a java.lang.NullPointerException in your method compareNums in line 136 of your class. Because you did not post line numbers I am not sure when the exception occurs.
I am assuming one of your arrays does not have any data in it or one or more of your arrays do not have 5 total entries of data in it because your for loop iterates 5 times. But again without seeing how or when your arrays are instantiated I do not think it is possible for anyone to confirm that is the cause of your problems. For example lotteryPlus2[] may only have data for lotteryPlus2[0],lotteryPlus2[1],and lotteryPlus2[2] so when j gets to 3 in the loop lotteryPlus2[3] does not exist and throws a java.lang.NullPointerException.
Also I am curious on why you use this for loop for (int i = 0; i < 1; i++){}
This loop only loops once no matter what so why have it there at all since your main method will always run at least once anyways? Honest question, I am a beginner programmer so you may be using it for something that I have no knowledge about.
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).
I'm trying to make a 2d array of an object in java. This object in java has several private variables and methods in it, but won't work. Can someone tell me why and is there a way I can fix this?
This is the exeception I keep getting for each line of code where I try to initialize and iterate through my 2d object.
"Exception in thread "main" java.lang.NullPointerException
at wumpusworld.WumpusWorldGame.main(WumpusWorldGame.java:50)
Java Result: 1"
Here is my main class:
public class WumpusWorldGame {
class Agent {
private boolean safe;
private boolean stench;
private boolean breeze;
public Agent() {
safe = false;
stench = false;
breeze = false;
}
}
/**
* #param args
* the command line arguments
* #throws java.lang.Exception
*/
public static void main(String [] args) {
// WumpusFrame blah =new WumpusFrame();
// blah.setVisible(true);
Scanner input = new Scanner(System.in);
int agentpts = 0;
System.out.println("Welcome to Wumpus World!\n ******************************************** \n");
//ArrayList<ArrayList<WumpusWorld>> woah = new ArrayList<ArrayList<WumpusWorld>>();
for (int i = 0 ; i < 5 ; i++) {
WumpusWorldObject [] [] woah = new WumpusWorldObject [5] [5];
System.out.println( "*********************************\n Please enter the exact coordinates of the wumpus (r and c).");
int wumpusR = input.nextInt();
int wumpusC = input.nextInt();
woah[wumpusR][wumpusC].setPoints(-3000);
woah[wumpusR][wumpusC].setWumpus();
if ((wumpusR <= 5 || wumpusC <= 5) && (wumpusR >= 0 || wumpusC >= 0)) {
woah[wumpusR][wumpusC].setStench();
}
if (wumpusC != 0) {
woah[wumpusR][wumpusC - 1].getStench();
}
if (wumpusR != 0) {
woah[wumpusR - 1][wumpusC].setStench();
}
if (wumpusC != 4) {
woah[wumpusR][wumpusC + 1].setStench();
}
if (wumpusR != 4) {
woah[wumpusR + 1][wumpusC].setStench();
}
System.out.println( "**************************************\n Please enter the exact coordinates of the Gold(r and c).");
int goldR = input.nextInt();
int goldC = input.nextInt();
woah[goldR][goldC].setGold();
System.out.println("***************************************\n How many pits would you like in your wumpus world?");
int numPits = input.nextInt();
for (int k = 0 ; k < numPits ; k++) {
System.out.println("Enter the row location of the pit");
int r = input.nextInt();
System.out.println("Enter the column location of the pit");
int c = input.nextInt();
woah[r][c].setPit();
if ((r <= 4 || c <= 4) && (r >= 0 || c >= 0)) {
woah[r][c].setBreeze();
}
if (c != 0) {
woah[r][c - 1].setBreeze();
}
if (r != 0) {
woah[r - 1][c].setBreeze();
}
if (c != 4) {
woah[r][c + 1].setBreeze();
}
if (r != 4) {
woah[r + 1][c].setBreeze();
}
}
for (int x = 0 ; x < 4 ; x++) {
int j = 0;
while (j < 4) {
agentpts = agentpts + woah[x][j].getPoints();
Agent [] [] k = new Agent [4] [4];
if (woah[x][j].getWumpus() == true) {
agentpts = agentpts + woah[x][j].getPoints();
System.out.println("You just got ate by the wumpus!!! THE HORROR!! Your score is " + agentpts);
}
if (woah[x][j].getStench() == true) {
k[x][j].stench = true;
System.out.println("You smell something funny... smells like old person.");
}
if (woah[x][j].getBreeze() == true) {
k[x][j].breeze = true;
System.out.println("You hear a breeze. yeah");
}
if (woah[x][j].getPit() == true) {
agentpts = agentpts + woah[x][j].getPoints();
System.out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH! you dumb bith, your dead now.");
}
// if breeze or stench, if breeze and stench, if nothing, etc then move.
k[x][j].safe = true;
// if(k[i][j].isSafe()!=true){
// } else { }
}
}
}
}
}
Here is my class object that I'm trying to implement:
package wumpusworld;
/**
*
* #author Jacob
*/
public class WumpusWorldObject {
private boolean stench;
private boolean breeze;
private boolean pit;
private boolean wumpus;
private boolean gold;
private int points;
private boolean safe;
public WumpusWorldObject(){
}
public boolean getPit() {
return pit;
}
public void setPit() {
this.pit = true;
}
public boolean getWumpus() {
return wumpus;
}
public void setWumpus() {
this.wumpus = true;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
public boolean getStench() {
return stench;
}
public void setStench() {
this.stench = true;
}
public boolean getBreeze() {
return breeze;
}
public void setBreeze() {
this.breeze = true;
}
public boolean getSafe() {
return safe;
}
public void setSafe() {
this.safe = true;
}
public void setGold(){
this.gold=true;
}
}
Creating array doesn't mean it will be automatically filled with new instances of your class. There are many reasons for that, like
which constructor should be used
what data should be passed to this constructor.
This kind of decisions shouldn't be made by compiler, but by programmer, so you need to invoke constructor explicitly.
After creating array iterate over it and fill it with new instances of your class.
for (int i=0; i<yourArray.length; i++)
for (int j=0; j<yourArray[i].length; j++)
yourArray[i][j] = new ...//here you should use constructor
AClass[][] obj = new AClass[50][50];
is not enough, you have to create instances of them like
obj[i][j] = new AClass(...);
In your code the line
woah[wumpusR][wumpusC].setPoints(-3000);
must be after
woah[wumpusR][wumpusC] = new WumpusWorldObject();
.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm not sure what's going on, but in the console I have a red 'stop' square that i can click to stop my program from running (Eclipse IDE) and my program is just running and the square stays red..?
EDIT:
my maze:
WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW
WSOOOOOOOOOOOOOOWOOOOOOOOOOOOOOOOOWOOOOOOOOOOOOOOOWOOOOOOW
WWOOOOOOOOOOOOOWWWWWWWWWWWWWOOOOOOOOOOWWWWWWWWWWWWWOOOOOOW
WWWWWWOOOOOOOOOOOOWWWWWWWOOOOOOOOOOOOWWWWWWWWWWWWWWWWOOOOW
WOOOOOOWWWWWWWWWWWWWWOOOOOOOOOOOWWWWWWWWOOOOOOOOOOOOOOOWWW
WOOOOWWWWWWWOOOOOOWWWWOOOOOOWWWWWWWWWWWOOOOWWWWWWWWWOWWWWW
WOOOWWWWWWWWWWWWOOWWWWWWWWWWWWOOOOOOOOOOOOWWWWWWWWWOOOOOWW
WOOWWWWWWWWWWWWWOOWWWWWWWWWWWWWWWWWOOOOOOOWWWWWWWWWWWWOOOW
WOWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWOOOOOOOWWWWWWWWWWWOOW
WOWWWWWWWWWWWWWOOOOOOOOOOOOOOOOOOOOOOOOOOOOWWWWWWWWWWWWOOW
WOOOOOOOOOOOOOOOOWWWWOOOOOOOOWWWWWWWOOOOOOWWWWWWWWWWWWWWFW
WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW
EDIT: here is my code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Stack;
import java.awt.Point;
public class MazeExplorer {
static Point startPoint = new Point();
static Point finishPoint = new Point();
final static int mazeHeight = 12;
final static int mazeWidth = 58;
static char[][] mazePoints = new char[mazeHeight][mazeWidth];
Stack<Point> pointsNotTraversed = new Stack<Point>();
Point pt = new Point();
static HashSet<Point> previousLocations = new HashSet<Point>();
static Stack<Point> nextPoints = new Stack<Point>();
public static void main(String[] args) throws FileNotFoundException{
System.out.println("Please enter the file name of your Maze");
Scanner console = new Scanner(System.in);
File f = new File(console.nextLine());
Scanner sc = new Scanner(f);
if(!sc.hasNextLine()){
System.out.println("Sorry, please enter a file name with the extension, that contains a maze!");
}
System.out.println("So, you want to know if your maze is solvable.....?");
for (int row = 0; row < mazeHeight && sc.hasNext(); row++) {
final String mazeRow = sc.next(); //Get the next row from the scanner.
mazePoints[row] = mazeRow.toCharArray(); //Convert the row into a char[].
}
//identify the finish point
for(int i = 0; i < mazeHeight; i++){
for(int j = 0; j<mazeWidth; j++){
if(mazePoints[i][j] == 'F'){
finishPoint = new Point(i, j);
}
}
}
// Identify the start point
for(int i = 0; i< mazeHeight; i++){
for(int j = 0; j < mazeWidth; j++){
if(mazePoints[i][j] == 'S'){
startPoint = new Point(i , j);
}
}
}
isTraversable(startPoint);
}
public static boolean isTraversable(Point current){
boolean isSolvable = false;
nextPoints.push(current);
do {
if(current.y < 11) {
if((mazePoints[current.y + 1][current.x] != ' ') && (mazePoints[current.y + 1][current.x] != 'W') ){ // below direction
nextPoints.push(new Point(current.y + 1, current.x));
mazePoints[current.y + 1][current.x] = ' ';
isTraversable(nextPoints.pop());
}
}
if(current.y > 0){
if (mazePoints[current.y - 1][current.x] != ' ' && mazePoints[current.y - 1][current.x] != 'W' ){ //up dir
nextPoints.push(new Point(current.y - 1, current.x));
mazePoints[current.y - 1][current.x] = ' '; //'X' marks where you've already been
isTraversable(nextPoints.pop());
}
}
if(current.x < 57){
if(mazePoints[current.y][current.x + 1] != ' ' && mazePoints[current.y][current.x + 1] != 'W'){ // to the right
nextPoints.push(new Point(current.y, current.x + 1));
mazePoints[current.y][current.x + 1] = ' ';
isTraversable(nextPoints.pop());
}
}
if(current.x > 0){
if(mazePoints[current.y][current.x - 1] != ' ' && mazePoints[current.y][current.x - 1] != 'W') { // to the left
nextPoints.push(new Point(current.y, current.x - 1));
mazePoints[current.y][current.x - 1] = ' ';
isTraversable(nextPoints.pop());
}
}
if(current.equals(finishPoint)){
isSolvable = true;
System.out.println("MAZE IS SOLVABLE, YAHOOOOOO!!!!");
}
} while(!current.equals('F') && !nextPoints.isEmpty());
return isSolvable;
}
}
As I suggested before, you just need to reconfigure your recursive method. I took the liberty of doing this but if you ever want to learn how to program you'll want to try and solve problems like these on your own. Or try to understand the logic of your solution before you start coding.
Your main problem is that you don't know what direction you want to go in with the method before you just jumped in and that was causing all sorts of errors with different things not being compatible with each other.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Stack;
import java.awt.Point;
public class TestCode {
static Point startPoint = new Point();
static Point finishPoint = new Point();
final static int mazeHeight = 12;
final static int mazeWidth = 58;
static char[][] mazePoints = new char[mazeHeight][mazeWidth];
Stack<Point> pointsNotTraversed = new Stack<Point>();
Point pt = new Point();
static HashSet<Point> previousLocations = new HashSet<Point>();
static Stack<Point> nextPoints = new Stack<Point>();
public static void main(String[] args) throws FileNotFoundException{
System.out.println("Please enter the file name of your Maze");
Scanner console = new Scanner(System.in);
File f = new File(console.nextLine());
Scanner sc = new Scanner(f);
if(!sc.hasNextLine()){
System.out.println("Sorry, please enter a file name with the extension, that contains a maze!");
}
System.out.println("So, you want to know if your maze is solvable.....?");
for (int row = 0; row < mazeHeight && sc.hasNext(); row++) {
final String mazeRow = sc.next(); //Get the next row from the scanner.
mazePoints[row] = mazeRow.toCharArray(); //Convert the row into a char[].
}
//identify the finish point
for(int i = 0; i < mazeHeight; i++){
for(int j = 0; j<mazeWidth; j++){
if(mazePoints[i][j] == 'F'){
finishPoint = new Point(i, j);
}
}
}
// Identify the start point
for(int i = 0; i< mazeHeight; i++){
for(int j = 0; j < mazeWidth; j++){
if(mazePoints[i][j] == 'S'){
startPoint = new Point(i , j);
}
}
}
System.out.println(isTraversable(startPoint));
}
public static boolean isTraversable(Point current){
mazePoints[current.x][current.y] = ' ';
if(current.y < 56 && current.y > 0 && current.x > 0 && current.x < 11){
if (mazePoints[current.x - 1][current.y] == 'O'){ // Up dir
Point upPoint = new Point(current.x-1, current.y);
nextPoints.push(upPoint);
}
if(mazePoints[current.x+1][current.y] == 'O'){ // Down dir
Point downPoint = new Point(current.x+1, current.y);
nextPoints.push(downPoint);
}
if(mazePoints[current.x][current.y + 1] == 'O'){ // to the right
Point rightPoint = new Point(current.x, current.y+1);
nextPoints.push(rightPoint);
}
if(mazePoints[current.x][current.y - 1] == 'O'){ // to the left
Point leftPoint = new Point(current.x, current.y-1);
nextPoints.push(leftPoint);
}
if(mazePoints[current.x - 1][current.y] == 'F' ||
mazePoints[current.x + 1][current.y] == 'F' ||
mazePoints[current.x][current.y - 1] == 'F' ||
mazePoints[current.x][current.y + 1] == 'F'){
System.out.println("MAZE IS SOLVABLE, YAHOOOOOO!!!!");
return true;
}
}
if(nextPoints.isEmpty()){
return false;
}
else{
current = nextPoints.pop();
}
return(isTraversable(current));
}
}
With the maze input:
WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW
WSOOOOOOOOOOOOOOWOOOOOOOOOOOOOOOOOWOOOOOOOOOOOOOOOWOOOOOOW
WWOOOOOOOOOOOOOWWWWWWWWWWWWWOOOOOOOOOOWWWWWWWWWWWWWOOOOOOW
WWWWWWOOOOOOOOOOOOWWWWWWWOOOOOOOOOOOOWWWWWWWWWWWWWWWWOOOOW
WOOOOOOWWWWWWWWWWWWWWOOOOOOOOOOOWWWWWWWWOOOOOOOOOOOOOOOWWW
WOOOOWWWWWWWOOOOOOWWWWOOOOOOWWWWWWWWWWWOOOOWWWWWWWWWOWWWWW
WOOOWWWWWWWWWWWWOOWWWWWWWWWWWWOOOOOOOOOOOOWWWWWWWWWOOOOOWW
WOOWWWWWWWWWWWWWOOWWWWWWWWWWWWWWWWWOOOOOOOWWWWWWWWWWWWOOOW
WOWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWOOOOOOOWWWWWWWWWWWOOW
WOWWWWWWWWWWWWWOOOOOOOOOOOOOOOOOOOOOOOOOOOOWWWWWWWWWWWWOOW
WOOOOOOOOOOOOOOOOWWWWOOOOOOOOWWWWWWWOOOOOOWWWWWWWWWWWWWOFW
WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW
Yields the following output:
So, you want to know if your maze is solvable.....?
MAZE IS SOLVABLE, YAHOOOOOO!!!!
true
I imported the file a different way, but you can change that back to whatever method you use previously.
Might be that you've started multiple programs and you have the "Show Console When Standard Output Changes" Not sure, but that explains one scenario. If you start task manager and find the program there you could try terminating it that way.
If it's stuck running and never completes you could try running your program in the Eclipse debugger, without any breakpoints.
Open the Debug tab (Open in from Window > Show View > Debug), suspend the thread by right clicking 'Thread [main] (Running)' and selecting 'Suspend'.
Then work your way up from the bottom of the stack, hopefully this will narrow it down enough for you to find where it blocks.
import java.util.Scanner;
import java.util.Stack;
public class test5 {
private int numRows;
private int numCols;
public test5(){
Scanner input = new Scanner(System.in);
System.out.println("Enter number of rows: ");
numRows = input.nextInt();
System.out.println("Enter number of cols: ");
numCols = input.nextInt();
Stack<Point>stack = new Stack<Point>();
stack.push(new Point(0,0));
while(!stack.isEmpty()){
if(currentPath(stack.pop(),stack)){
System.out.println("Maze is solvable");
}
}
}
public static void main(String[]args){
new test5();
}
private boolean currentPath(Point point, Stack<Point>stack){
int currentRow = point.getRow();
int currentCol = point.getCol();
while(currentRow!=numRows-1 || currentCol!=numCols-1){
boolean canGoRight = canGoRight(currentRow,currentCol);
boolean canGoUp = canGoUp(currentRow,currentCol);
boolean canGoDown = canGoDown(currentRow,currentCol);
if(canGoRight){
if(canGoUp){
stack.push(new Point(currentRow-1,currentCol));
}
if(canGoDown){
stack.push(new Point(currentRow+1,currentCol));
}
currentCol = currentCol+1;
}
else{
if(canGoUp){
if(canGoDown){
stack.push(new Point(currentRow+1,currentCol));
}
currentRow = currentRow-1;
}
else if(canGoDown){
currentRow = currentRow+1;
}
else{
return false;
}
}
}
return true;
}
private boolean canGoUp(int row, int col){
return row-1>=0;
}
private boolean canGoRight(int row, int col){
return col+1<numCols;
}
private boolean canGoDown(int row, int col){
return row+1<numRows;
}
class Point{
private int row;
private int col;
public Point(int row, int col){
this.row = row;
this.col = col;
}
public int getRow(){
return row;
}
public int getCol(){
return col;
}
}
}