(Arraylist) Crashes when user defined String input - java

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.

Related

Why does it display the value "null" if the conditions of the method are met?

I'm trying to compile my first major program. Unfortunately in getBestFare() I get "null" coming out all the time. And it shouldn't! I'm asking you guys for help what's wrong.
I rebuilt the entire getBestFare() method but unfortunately it keeps coming up with "null". The earlier code was a bit more messy. Now it's better, but it still doesn't work.
public class TransitCalculator {
public int numberOfDays;
public int transCount;
public TransitCalculator(int numberOfDays, int transCount) {
if(numberOfDays <= 30 && numberOfDays > 0 && transCount > 0){
this.numberOfDays = numberOfDays;
this.transCount = transCount;
} else {
System.out.println("Invalid data.");
}
}
String[] length = {"Pay-per-ride", "7-day", "30-day"};
double[] cost = {2.75, 33.00, 127.00};
public double unlimited7Price(){
int weekCount = numberOfDays/7;
if (numberOfDays%7>0){
weekCount+=1;
}
double weeksCost = weekCount * cost[1];
return weeksCost;
}
public double[] getRidePrices(){
double price1 = cost[0];
double price2 = ((cost[1]*unlimited7Price()) / (unlimited7Price() * 7));
double price3 = cost[2] / numberOfDays;
double[] getRide = {price1, price2, price3};
return getRide;
}
public String getBestFare(){
int num = 0;
for (int i = 0; i < getRidePrices().length; i++) {
if(getRidePrices()[i] < getRidePrices()[num]){
return "You should get the " + length[num] + " Unlimited option at " + getRidePrices()[num]/transCount + " per ride.";
}
}
return null;
}
public static void main(String[] args){
TransitCalculator one = new TransitCalculator(30, 30);
System.out.println(one.unlimited7Price());
System.out.println(one.getRidePrices()[2]);
System.out.println(one.getBestFare());
}
}

Passing Values from Constructor to a Method

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);

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).

Missing Format Argument Exception

When compiling I get a "java.util.MissingFormatArgumentException: null (in java.util.Formater) I do not know why.
"Exception in thread "main" java.util.MissingFormatArgumentException: Format specifier 's'"
Please Help.
import java.lang.*;
import java.util.Random;
import java.util.Scanner;
import static java.lang.System.out;
public class DartSimV1
{
static double[] SiXX(int Money)
{
double[] VarXX;
VarXX = new double[Money];
int IBS;
IBS = 0;
if (IBS < VarXX.length) {
do {
VarXX[IBS] = Math.random();
IBS++;
} while (IBS < VarXX.length);
}
return VarXX;
}
public static double[] SiYY(int Money)
{
double[] VarYY;
VarYY = new double[Money];
int IBS;
IBS = 0;
while (true) {
if (false) {
break;
}
if (!(IBS < VarYY.length)) {
break;
}
VarYY[IBS]=Math.random();
IBS++;
}
return VarYY;
}
public static double WhatPie(double[] IBS,double[] YYCoord)
{
double [] VarXX;
VarXX = IBS;
double [] VarYY;
VarYY = YYCoord;
double Totals;
Totals = 0;
double Contacts;
Contacts = 0;
int IBO;
IBO = 0;
if (IBO < VarXX.length) {
if ((Math.pow(VarXX[IBO], 2) + Math.pow(VarYY[IBO], 2)) <= 1) {
Totals++;
Contacts++;
} else Totals++;
IBO++;
if (IBO < VarXX.length) {
do {
if ((Math.pow(VarXX[IBO], 2) + Math.pow(VarYY[IBO], 2)) <= 1) {
Totals++;
Contacts++;
} else {
Totals++;
}
IBO++;
} while (IBO < VarXX.length);
}
}
double PIE;
PIE = 4 *
(Contacts
/
Totals);
return PIE;
}
public static void Answers(int Done, double New)
{
double PIE;
PIE = New;
System.out.printf("Trial [" + Done +"]: PIE = %11.3f%s",PIE);
}
public static void PieA(double[] New, int Done)
{
double[] PIE;
PIE = New;
int trials;
trials = Done;
double Totals;
Totals = 0.0;
int i;
i = 0;
if (i < PIE.length) {
double IBS;
IBS = PIE[i];
Totals += IBS;
i++;
if (i < PIE.length) {
do {
IBS = PIE[i];
Totals += IBS;
i++;
} while (i < PIE.length);
}
}
double PieA;
PieA = Totals/trials;
System.out.printf("AVG for π = %11.3f%s",PieA);
}
public static void main(String[] args)
{
Scanner show;
show = new Scanner(System.in);
System.out.print("# per trials?: ");
int dPt;
dPt = show.nextInt();
System.out.print("Trial #'s?: ");
int nTri;
nTri = show.nextInt();
double[] PieA;
PieA = new double[nTri];
int IBS=0;
while (IBS<nTri) {
double [] VarXX;
VarXX = SiXX(dPt);
double [] VarYY;
VarYY = SiYY(dPt);
double PIE;
PIE = WhatPie(VarXX,VarYY);
PieA[IBS]=PIE;
Answers(IBS,PIE);
IBS++;
}
PieA(PieA,nTri);
}
}
System.out.printf("Trial [" + Done +"]: PIE = %11.3f%s",PIE); has 2 parameters: one float %11.3f and one string %s. You've only given it one value to print PIE. It needs two - a float and a string.
Also: The exception gives you the full details of the problem - including the line number. You should include that in your question to give people the best chance of answering.

Method Not Displaying Properly

The method "aboveAverage" in the following code is not displaying correctly and I've tried everything I can. Could someone please explain what's going wrong?
My code:
import java.util.*;
public class DailyCatch
{
private int fishermanID, fisherID;
private String dateOfSample, date;
private double[] fishCaught = new double[10];
private int currWeight = 0;
private String summary;
private double average;
private int aboveAvg;
public DailyCatch() { }
public DailyCatch (int fishermanID, String dateOfSample)
{
fisherID = fishermanID;
date = dateOfSample;
}
public DailyCatch (int fishermanID, String dateOfSample, String weight)
{
this(fishermanID, dateOfSample);
readWeights(weight);
}
public void addFish(double weight)
{
if (currWeight > 10)
{
// array full
}
else
{
fishCaught[currWeight] = weight;
currWeight += 1; // update current index of array
}
}
private void readWeights(String weightsAsString)
{
String[] weightsRead = weightsAsString.split("\\s+");
for (int i = 0; i < weightsRead.length; i++)
{
this.addFish(Double.parseDouble(weightsRead[i]));
}
}
public String toString()
{
return "Fisherman ID: " + fisherID + "\nDate:" + date + "\nFish Caught with Weights: " + Arrays.toString(fishCaught);
}
public void printWeights()
{
for (int i = 0; i < fishCaught.length; i++)
{
System.out.println(fishCaught[i]);
}
}
public double averageWeight()
{
double sum = 0;
double count = 0;
for (int i = 0; i < fishCaught.length; i++)
{
if (fishCaught[i] != 0)
{
sum += fishCaught[i];
count += 1;
average = sum/count;
}
}
return average;
}
public String getSummary()
{ int storyTellerCount = 0;
int keeperCount = 0;
int throwBackCount = 0;
for (int i = 0; i < fishCaught.length; i++)
{
if (fishCaught[i] > 5)
{
storyTellerCount++;
}
else if (fishCaught[i] >=1 && fishCaught[i] <= 5)
{
keeperCount++;
}
else if (fishCaught[i] < 1 && fishCaught[i] > 0)
{
throwBackCount++;
}
} String summary = ("\nStoryteller - " + storyTellerCount+ "\nKeeper - " + keeperCount + "\nThrowback - " + throwBackCount);
return summary;
}
public int aboveAverage()
{
int greatAvgCount = 0;
for (int i = 0; i < fishCaught.length; i++)
{
if (fishCaught[i] > average)
{
aboveAvg = greatAvgCount++;
}
}
return aboveAvg;
}
}
Test Code:
public class BigBass
{
public static void main (String[]args)
{
//Part 1
DailyCatch monday1 = new DailyCatch(32, "4/1/2013", "4.1 5.5 2.3 0.5 4.8 1.5");
System.out.println(monday1);
//Part 2
DailyCatch monday2 = new DailyCatch(44, "4/1/2013");
System.out.println(monday2);
monday2.addFish(2.1);
monday2.addFish(4.2);
System.out.println(monday2);
//Part 3
System.out.println("\n\nSUMMARY OF FISHERMAN 32");
System.out.println(monday1.getSummary());
//Part 4
double avg = monday1.averageWeight();
System.out.printf("\nThere are %d fish above the average weight of %.1f.", monday1.aboveAverage(), avg);
}
}
I just need to get Part 4 to work here. What it does is return that there have been 2 fish caught that are above average when I know it should be 3. The average is 3.1.
A simple mistake.
public int aboveAverage() {
int greatAvgCount = 0;
for (int i = 0; i < fishCaught.length; i++) {
if (fishCaught[i] > 3.1) {
greatAvgCount++; // no 'return'
}
}
return greatAvgCount;
}
if (fishCaught[i] > 3.1)
{
return greatAvgCount++;
}
First try : 4.1 > 3.1
true
returns 0 ++ which is 0 basically
You can increment the counter inside the loop and keep the return statement for the end only.
try
public int aboveAverage() {
int greatAvgCount = 0;
for (int i = 0; i < fishCaught.length; i++) {
if (fishCaught[i] > 3.1) {
greatAvgCount++;
}
}
return greatAvgCount;
}
This line is your problem,
return greatAvgCount++;
you are incrimenting greatAvgCount then returning its initial value, there should be no "return" on this line
The aboveAverage method should be
public int aboveAverage()
{
int greatAvgCount = 0;
for (int i = 0; i < fishCaught.length; i++)
{
if (fishCaught[i] > 3.1)
{
greatAvgCount++;
}
}
return greatAvgCount;
}
Also, you may just be doing it for debug, in which case fair enough, but hardcoding the "average" as 3.1 is generally considered bad practice. If you want average to be always 3.1 (i.e. its a global average that you've looked up from a book then its more usual to declare a static variable called double AVERAGE=3.1 and then use that where ever average is required, that way if the "book value" changes you only need to change average in one place in your code. If average is calculated from your data obviously you should use the calculated value.
Also not directly related to your problem but why are you using an array for your caught fish with a predefined maximum of 10. If you used an ArrayList you could add to it as you saw fit and it would auto expand to accommodate
private double[] fishCaught = new double[10];
becomes
private ArrayList<Double> fishCaught = new ArrayList<Double>();

Categories