Fix NullPointerException? [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
How could I get the program to output all the information? IT currently returns a NullPointException error. Thanks.
I am supposed to use the delete methods just as they are, I cannot change them, but I am sure there must be something I can do.
public class TestCandidate7
{
public static int getTotal(Candidate[] election)
{
int total = 0;
for(Candidate candidate : election )
{
total += candidate.numVotes;
}
return total;
}
public static void printResults(Candidate[] election)
{
double percent;
System.out.println("Candidate Votes Received % of Total Votes");
for (int x = 0; x < election.length; x++)
{
percent = (double) (election[x].votes()) / getTotal(election) * 100;
System.out.printf("%-15s %10d %20.0f", election[x].getName(), election[x].votes(), percent);
System.out.println();
}
}
public static void deleteByLoc(Candidate[] election,
int location)
{
if ((location > 0) && (location < election.length))
{
//move items up in the array -
for(int index = location; index < election.length -1; index++)
election[index] = election[index + 1];
election[election.length-1] = null;
}
}
public static void deleteByName(Candidate[] election,
String find)
{
int location = 0;
int index;
// find location of item you want to delete
for(index = 0; index < election.length; index++)
if ((election[index] != null) && (election[index].getName().equals(find)))
{
location = index;
break;
}
else if (election[index] == null)
{
location = -1;
break;
}
if ((index != election.length) && (location >= 0))
{ //move items up in the array
for(index = location; index < election.length -1; index++)
election[index] = election[index + 1];
election[election.length-1] = null;
}
}
public static void main(String[] args)
{
Candidate[] election = new Candidate[10];
// create election
election[0] = new Candidate("John Smith", 5000);
election[1] = new Candidate("Mary Miller", 4000);
election[2] = new Candidate("Michael Duffy", 6000);
election[3] = new Candidate("Tim Robinson", 2500);
election[4] = new Candidate("Joe Ashtony", 1800);
election[5] = new Candidate("Mickey Jones", 3000);
election[6] = new Candidate("Rebecca Morgan", 2000);
election[7] = new Candidate("Kathleen Turner", 8000);
election[8] = new Candidate("Tory Parker", 500);
election[9] = new Candidate("Ashton Davis", 10000);
System.out.println("Original results:");
System.out.println();
printResults(election);
System.out.println();
System.out.println("Total of votes in election: " + getTotal(election) );
System.out.println();
deleteByLoc(election, 6);
System.out.println("Deleted location 6:");
System.out.println();
printResults(election);
System.out.println();
System.out.println("Total of votes in election: " + getTotal(election) );
System.out.println();
deleteByName(election, "Kathleen Turner");
System.out.println("Deleted Kathleen Turner:");
System.out.println();
printResults(election);
System.out.println();
System.out.println("Total of votes in election: " + getTotal(election) );
System.out.println();
}
}
Candidate
public class Candidate
{
// instance variables
int numVotes;
String name;
/**
* Constructor for objects of class InventoryItem
*/
public Candidate(String n, int v)
{
// initialise instance variables
name = n;
numVotes = v;
}
public int votes()
{
return numVotes;
}
public void setVotes(int num)
{
numVotes = num;
}
public String getName()
{
return name;
}
public void setName(String n)
{
name = n;
}
public String toString()
{
return name + " received " + numVotes + " votes.";
}
}

When you "delete" array elements, after the shift you assign null to the most right element of the array.
In your getTotal() you traverse the entire array and retrieve the value of numVotes for each element. When you reach the null element you are getting the exception since null does not have any fields..

Related

Invalid array display

Good day, I have the following assignment:
https://prnt.sc/113pc7j
My problem is the first assignment of the fourth item. I prescribed filling the array with random objects, however, when I want to display this array on the screen, I get different results all the time.
My code:
The interface itself:
interface VehicleAndWorkers
{
String cars();
}
First class that implements the interface:
public class TaxiStation implements VehicleAndWorkers{
TrucksLogistic trucks = new TrucksLogistic();
public String[] cars = {"KIA", "Hyundai", "Volkswagen", "Lada", "Datsun", "Skoda"};
int quantCars = 150;
int workers = 300;
public String cars() {
System.out.println("List of models of our taxi fleet: ");
for (int i = 0; i < cars.length; i++) {
System.out.println(cars[i]);
}
return null;
}
#Override
public boolean equals(Object obj)
{
return trucks.quantTrucks == this.quantCars;
}
#Override
public int hashCode() {
return Objects.hash(trucks, quantCars);
}
#Override
public String toString() {
return cars();
}
}
Second class that implements the interface:
public class TrucksLogistic implements VehicleAndWorkers {
String[] trucks = {"Kenworth W900", "Volvo FH16", "Scania R730", "MAN TGS 18.400", "МАЗ 6430",
"КАМАЗ-5490 НЕО 2"};
int quantTrucks = 40;
int workers = 100;
public String cars()
{
System.out.println("Our company model list: ");
for (int i = 0; i < trucks.length; i++)
{
System.out.println(trucks[i]);
}
System.out.println("Amount of workers: " + workers);
System.out.println("Number of trucks: " + quantTrucks);
System.out.println("The ratio of the number of truck models to the number of trucks: " +
Math.round(trucks.length / quantTrucks));
return null;
}
#Override
public String toString() {
return cars();
}
}
The class in which I tried to implement working with ArrayList (filling, displaying, etc.):
public class InterfaceArray {
ArrayList<VehicleAndWorkers> array = new ArrayList<>();
public void setArray() {
int randomLength = (int) Math.floor(random() * 10);
for (int i = 0; i < randomLength; i++) {
Random random = new Random();
int minRandomNum = 1;
int maxRandomNum = 2;
int diffRandomNum = maxRandomNum - minRandomNum;
int randomNum = random.nextInt(diffRandomNum + 1) + minRandomNum;
if (randomNum == 1) {
array.add(new TrucksLogistic() {
#Override
public String cars() {
int num = (int) Math.floor(random() * trucks.length);
quantTrucks = (int) Math.floor(random() * 100);
Random random = new Random();
int minWorkers = quantTrucks;
int maxWorkers = 200;
int diffWorkers = maxWorkers - minWorkers;
workers = random.nextInt(diffWorkers + 1);
workers += minWorkers;
System.out.println("Number of trucks: " + quantTrucks);
System.out.println("Amount of workers: " + workers);
System.out.println("Average number of workers per truck: " + Math.round(workers /
quantTrucks));
return "Priority truck brand/model: " + trucks[num];
}
});
} else {
array.add(new TaxiStation() {
#Override
public String cars() {
int num = (int) Math.floor(random() * cars.length);
quantCars = (int) Math.floor(random() * 100);
Random random = new Random();
int minWorkers = quantCars;
int maxWorkers = 200;
int diffWorkers = maxWorkers - minWorkers;
workers = random.nextInt(diffWorkers + 1);
workers += minWorkers;
System.out.println("Number of passenger cars: " + quantCars);
System.out.println("Amount of workers: " + workers);
System.out.println("Average number of employees per vehicle: " + Math.round(workers / quantCars));
return "Priority car brand/model:" + cars[num];
}
});
}
}
}
public void getArray() {
for (VehicleAndWorkers element : array) {
System.out.println("");
System.out.println(element);
System.out.println("");
}
}
public void sameElements() {
//// Set<VehicleAndWorkers> arrayTwo = new LinkedHashSet<>(array);
//// for (VehicleAndWorkers element : arrayTwo)
//// System.out.println(element + "\n");
//
// for (int element = 0; element < array.size() - 1; element++)
// {
// for (int i = element + 1; i < array.size(); element++)
// {
// if (array.get(element).equals(element + 1))
// {
// arrayTwo.add(array.get(element + 1));
// }
// }
// array.remove(array.get(element));
// }
// for (VehicleAndWorkers element : arrayTwo)
// System.out.println(element.toString());
}
public void sameTypeElements() {
ArrayList<VehicleAndWorkers> arrayTwo = new ArrayList<>();
// for (VehicleAndWorkers element : array)
// {
// if (element)
// }
}
}
Well, the class in which the methods from the previous class are applied:
public class ConsoleInterface {
void doChoice()
{
InterfaceArray interfaceArray = new InterfaceArray();
printOptions();
Scanner scan = new Scanner(System.in);
int choice = scan.nextInt();
while (choice >= 0 && choice < 5) {
if (choice == 0) {
interfaceArray.setArray();
interfaceArray.getArray();
printOptions();
choice = scan.nextInt();
}
else if (choice == 1) {
interfaceArray.setArray();
printOptions();
choice = scan.nextInt();
}
else if (choice == 2) {
interfaceArray.sameElements();
printOptions();
choice = scan.nextInt();
}
else if (choice == 3) {
interfaceArray.sameTypeElements();
printOptions();
choice = scan.nextInt();
}
else if (choice == 4) {
interfaceArray.getArray();
printOptions();
choice = scan.nextInt();
}
}
}
void printOptions()
{
System.out.println("Choose an action: \n");
System.out.println("0 - Fill the array with random elements and display it on the screen. \n");
System.out.println("1 - Fill the array with random elements. \n");
System.out.println("2 - Find objects in the array,\n" +
" whose functional method returns the same result. \n");
System.out.println("3 - Split the original array into two arrays, \n" +
" which will store the same type of elements. \n");
System.out.println("4 - Display the array(-s) to the screen.\n");
System.out.println("Any key - Exit the application.\n");
}
}
An example of how the program works:
I fill the array and immediately output it to the console: https://prnt.sc/113qmkr
I get the result:
https://prnt.sc/113qurt
https://prnt.sc/113qvaq
I try again to display all the objects in the array: https://prnt.sc/113qvz4
And... I get completely different results:
https://prnt.sc/113qwhx
https://prnt.sc/113qwps
Moreover, as you may have noticed, the length of the array is preserved, but the objects themselves are already different.
Honestly, I don't know what the problem might be, the teacher at the university also threw up his hands, so I will be glad to any criticism, comments and suggestions. Thank you in advance.

Why won't my bubble sort sort my array of objects?

I've created a program with an object called CarlysCatering. I'm trying to sort the CarlysCatering objects by number of guests.
I've tried using a bubble sort but I get an error message.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
CarlysCatering[] event = new CarlysCatering[100];
event[0] = new CarlysCatering(10, "A547", "6874714145", 0);
event[1] = new CarlysCatering(100, "B527", "6874874945", 2);
event[2] = new CarlysCatering(50, "C546", "6874785145", 3);
event[3] = new CarlysCatering(40, "L577", "6874321485", 1);
event[4] = new CarlysCatering(70, "A111", "6874714145", 4);
event[5] = new CarlysCatering(90, "K222", "6874974855", 2);
event[6] = new CarlysCatering(11, "F798", "6875555555", 3);
event[7] = new CarlysCatering(17, "T696", "6474763898", 0);
//SORT
int selection = 0;
do {
System.out.println("1 - sort by eventID. 2 - sort by number of guests. 3 - sort by event type. 4 - quit");
selection = input.nextInt();
input.nextLine();
if(selection == 1) {
}
if(selection == 2) {
int n = event.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (event[j].getGuests() > event[j + 1].getGuests()) {
// swap arr[j+1] and arr[i]
CarlysCatering temp = event[j];
event[j] = event[j + 1];
event[j + 1] = temp;
}
}
}
}
} while (selection != 4);
//Print totals
event[0].getTotals(); event[1].getTotals(); event[2].getTotals(); event[3].getTotals(); event[4].getTotals(); event[5].getTotals(); event[6].getTotals(); event[7].getTotals();
}
////////////////////////////////////////////////////// STATIC METHODS //////////////////////////////////////////////////////////////////////
}
public class CarlysCatering {
public static final int PRICE_PER_GUEST_HIGH = 35;
public static final int PRICE_PER_GUEST_LOW = 32;
public static final int CUTOFF_VALUE_LARGE = 49;
private int guests;
private int totalPrice;
private String eventID;
private String phoneNumber;
private String eventType;
private boolean largeEvent;
///////////////////////////////////////////////////// CONSTRUCTORS //////////////////////////////////////////////////////////////////
CarlysCatering() {
this.guests = 0;
this.eventID = "A000";
this.phoneNumber = "0000000000";
}
CarlysCatering(int guests, String eventID, String phoneNumber, int eventType) {
this.guests = guests;
this.eventID = eventID;
//Phone Number formatting
String phoneNumber2 = "";
int count = 0;
for(int i = 0; i < phoneNumber.length(); i++) {
if (Character.isDigit(phoneNumber.charAt(i))) {
phoneNumber2 += phoneNumber.charAt(i);
count += 1;
}
}
if (count != 10) {
this.phoneNumber = "0000000000";
} else {
String phoneNumber3 = "(" + phoneNumber2.substring(0,3) + ") " + phoneNumber2.substring(3,6) + "-" + phoneNumber2.substring(6,10);
this.phoneNumber = phoneNumber3;
}
//Event type formatting
final String[] eventString = new String[5];
eventString[0] = "wedding"; eventString[1] = "baptism"; eventString[2] = "birthday"; eventString[3] = "corporate"; eventString[4] = "other";
if(eventType > -1 && eventType < 5) {
this.eventType = eventString[eventType];
} else {
this.eventType = eventString[4];
}
}
///////////////////////////////////////////////////////// SETTERS AND GETTERS /////////////////////////////////////////////////
//Setters
public void setEventID(String eventID) {
this.eventID = eventID;
}
public void setGuests(int guests) {
this.guests = guests;
}
public void setPhoneNumber(String phoneNumber) {
String phoneNumber2 = "";
int count = 0;
for (int i = 0; i < phoneNumber.length(); i++) {
if (Character.isDigit(phoneNumber.charAt(i))) {
phoneNumber2 += phoneNumber.charAt(i);
count += 1;
}
}
if (count != 10) {
this.phoneNumber = "0000000000";
} else {
String phoneNumber3 = "(" + phoneNumber2.substring(0, 3) + ") " + phoneNumber2.substring(3, 6) + "-" + phoneNumber2.substring(6, 10);
this.phoneNumber = phoneNumber3;
}
}
public void setEventType(String eventType) {
this.eventType = eventType;
}
//Getters
public int getTotalPrice() {
return totalPrice;
}
public int getGuests() {
return guests;
}
public String getEventID() {
return eventID;
}
public String getPhoneNumber() {
return phoneNumber;
}
public String getEventType() {
return eventType;
}
/////////////////////////////////////////////////////// ADDITIONAL METHODS ///////////////////////////////////////////////////////////////////
public void isLargeEvent() {
if (this.guests > CUTOFF_VALUE_LARGE) {
largeEvent = true;
System.out.println("Yes this is a large event.");
} else {
largeEvent = false;
System.out.println("This is not a large event");
}
}
public void getTotals() {
boolean largeEvent = false;
if(this.guests > CUTOFF_VALUE_LARGE) {
largeEvent = true;
this.totalPrice = this.guests * PRICE_PER_GUEST_HIGH;
} else {
largeEvent = false;
this.totalPrice = this.guests * PRICE_PER_GUEST_LOW;
}
System.out.println("The number of guests attending event " + this.eventID + " " + this.eventType + " is: " + this.guests + ". The total price is $" + this.totalPrice);
System.out.println("Large event: " + largeEvent);
System.out.println("The phone number on file is " + this.phoneNumber);
}
// Static methods
public static void showMotto() {
System.out.println("*****Carly's makes the food that makes it a party.*****");
}
}
The error message I get when I try to sort by guests is Exception in thread "main" java.lang.NullPointerException and then error code exit -1. The line that's causing the error is:
if (event[j].getGuests() > event[j + 1].getGuests()) {
You create an Array with the size 100.
After that, you fill it from index 0 to 7.
Every other place of the array remains null but the length is 100.
Then, you try to sort the array.
This throws a NullPointerException when you try to dereference (access) the 8. element:
event[j+1].getGuests()
I think you should use a smaller array(size 8) or a List.

user input still stored after exceeding array length

Can someone see why the user can enter more than 27 apple, blueberry, or peanut pies? Even after declaring a final int for the max number of each type of pie.
The object here is to continually prompt the user for type of pie until the user wants to quit. Each time one of the valid inputs is entered it is stored in it's own array. After the user has indicated they are finished, calculations are done and a message is printed.
import javax.swing.JOptionPane;
public class CalcPieProfit {
public static void main(String[] args) {
final int MAX_PER_TYPE = 27;
int appleTotal = 0;
int blueberryTotal = 0;
int peanutTotal = 0;
String typeOfPie = getPieType();
while (!typeOfPie.equalsIgnoreCase("q")) {
if (typeOfPie.equalsIgnoreCase("apple")) {
String[] appleArray = fillApple(typeOfPie, MAX_PER_TYPE);
appleTotal++;
}
else if (typeOfPie.equalsIgnoreCase("blueberry")) {
String[] blueberryArray = fillBlueberry(typeOfPie, MAX_PER_TYPE);
blueberryTotal++;
}
else if (typeOfPie.equalsIgnoreCase("peanut")) {
String[] peanutArray = fillPeanut(typeOfPie, MAX_PER_TYPE);
peanutTotal++;
}
typeOfPie = getPieType();
}
if (typeOfPie.equalsIgnoreCase("q")) {
int totalPies = calcTotalPies(appleTotal, blueberryTotal, peanutTotal);
double profit = calcProfit(appleTotal, blueberryTotal, peanutTotal);
printReport(totalPies, appleTotal, blueberryTotal, peanutTotal, profit);
}
}
public static String getPieType() {
String pieType;
do {
try {
pieType = JOptionPane.showInputDialog("Enter a pie type:");
}
catch (NumberFormatException e) {
pieType = "";
}
if (!pieType.equalsIgnoreCase("apple") && !pieType.equalsIgnoreCase("blueberry") &&
!pieType.equalsIgnoreCase("peanut") && !pieType.equalsIgnoreCase("q")) {
JOptionPane.showMessageDialog(null, "Enter 'apple', 'blueberry', 'peanut', or 'q' only.");
}
} while (!pieType.equalsIgnoreCase("apple") && !pieType.equalsIgnoreCase("blueberry") &&
!pieType.equalsIgnoreCase("peanut") && !pieType.equalsIgnoreCase("q"));
return pieType;
}
public static String[] fillApple(String typeOfPie, int MAX_PER_TYPE) {
String[] appleArray = new String[MAX_PER_TYPE];
for (int i = 0; i < appleArray.length; i++) {
appleArray[i] = typeOfPie;
}
return appleArray;
}
public static String[] fillBlueberry(String typeOfPie, int MAX_PER_TYPE) {
String[] blueberryArray = new String[MAX_PER_TYPE];
for (int i = 0; i < blueberryArray.length; i++) {
blueberryArray[i] = typeOfPie;
}
return blueberryArray;
}
public static String[] fillPeanut(String typeOfPie, int MAX_PER_TYPE) {
String[] peanutArray = new String[MAX_PER_TYPE];
for (int i = 0; i < peanutArray.length; i++) {
peanutArray[i] = typeOfPie;
}
return peanutArray;
}
public static int calcTotalPies(int appleTotal, int blueberryTotal, int peanutTotal) {
int total = appleTotal + blueberryTotal + peanutTotal;
return total;
}
public static double calcProfit (int appleTotal, int blueberryTotal, int peanutTotal) {
final double APPLE_PROFIT = 5.94;
final double BLUEBERRY_PROFIT = 5.89;
final double PEANUT_PROFIT = 6.95;
double profit = (APPLE_PROFIT * appleTotal) + (BLUEBERRY_PROFIT * blueberryTotal) +
(PEANUT_PROFIT * peanutTotal);
return profit;
}
public static void printReport(int totalPies, int appleTotal, int blueberryTotal, int peanutTotal, double profit) {
if (totalPies > 0) {
JOptionPane.showMessageDialog(null,
"Pie Report\n\n" +
"Total pies: " + totalPies +
"\nTotal of apple pie: " + appleTotal +
"\nTotal of blueberry pie: " + blueberryTotal +
"\nTotal of peanut butter pie: " + peanutTotal +
"\nTotal profit: $" + String.format("%.2f", profit));
}
else {
JOptionPane.showMessageDialog(null, "Enjoy your day off.");
}
}
}
You are not really using the String[]s appleArray, blueberryArray and peanutArray - they are created in their respective method but not used anywhere else. For calculating the profits, you are (rightfully) only the total variables.
Instead of
if (typeOfPie.equalsIgnoreCase("apple")) {
String[] appleArray = fillApple(typeOfPie, MAX_PER_TYPE);
appleTotal++;
}
you should do something like
if (typeOfPie.equalsIgnoreCase("apple")) {
if (appleTotal >= MAX_PER_TYPE) {
JOptionPane.showMessageDialog(null, "Too many apples.");
} else {
appleTotal++;
}
}
(and the same for other pie types).
You're redeclaring the pie arrays each time you go to add them.
public static String[] fillApple(String typeOfPie, int MAX_PER_TYPE) {
String[] appleArray = new String[MAX_PER_TYPE];
for (int i = 0; i < appleArray.length; i++) {
appleArray[i] = typeOfPie;
}
return appleArray;
}
Each time you call this method, a new "appleArray" is generated. If you want it to persist between calls to this method, declare the appleArray as private static outside of the loop, and reference that instead.

Mean, Median, and Mode - Newb - Java

We had a lab in Comsci I couldn't figure out. I did a lot of research on this site and others for help but they were over my head. What threw me off were the arrays. Anyway, thanks in advance. I already got my grade, just want to know how to do this :D
PS: I got mean, I just couldn't find the even numbered median and by mode I just gave up.
import java.util.Arrays;
import java.util.Random;
public class TextLab06st
{
public static void main(String args[])
{
System.out.println("\nTextLab06\n");
System.out.print("Enter the quantity of random numbers ===>> ");
int listSize = Expo.enterInt();
System.out.println();
Statistics intList = new Statistics(listSize);
intList.randomize();
intList.computeMean();
intList.computeMedian();
intList.computeMode();
intList.displayStats();
System.out.println();
}
}
class Statistics
{
private int list[]; // the actual array of integers
private int size; // user-entered number of integers in the array
private double mean;
private double median;
private int mode;
public Statistics(int s)
{
size = s;
list = new int[size];
mean = median = mode = 0;
}
public void randomize()
{
Random rand = new Random(12345);
for (int k = 0; k < size; k++)
list[k] = rand.nextInt(31) + 1; // range of 1..31
}
public void computeMean()
{
double total=0;
for (int f = 0; f < size; f++)
{
total = total + list[f];
}
mean = total / size;
}
public void computeMedian()
{
int total2 = 0;
Arrays.sort(list);
if (size / 2 == 1)
{
// total2 =
}
else
{
total2 = size / 2;
median = list[total2];
}
}
public void computeMode()
{
// precondition: The list array has exactly 1 mode.
}
public void displayStats()
{
System.out.println(Arrays.toString(list));
System.out.println();
System.out.println("Mean: " + mean);
System.out.println("Median: " + median);
System.out.println("Mode: " + mode);
}
}
Here are two implementations for your median() and mode() methods:
public void computeMedian() {
Arrays.sort(list);
if ( (list.size & 1) == 0 ) {
// even: take the average of the two middle elements
median = (list[(size/2)-1] + list[(size/2)]) / 2;
} else {
// odd: take the middle element
median = list[size/2];
}
}
public void computeMode() {
// precondition: The list array has exactly 1 mode.
Map<Integer, Integer> values = new HashMap<Integer, Integer>();
for (int i=0; i < list.size; ++i) {
if (values.get(list[i]) == null) {
values.put(list[i], 1);
} else {
values.put(list[i], values.get(list[i])+1);
}
}
int greatestTotal = 0;
// iterate over the Map and find element with greatest occurrence
Iterator it = values.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
if (pair.getValue() > greatestTotal) {
mode = pair.getKey();
greatestTotal = pair.getValue();
}
it.remove();
}
}

All my objects change in my arraylist

I'm adding a new object(class) to an ArrayList, but when I try to get variables from the objects in my ArrayList, the variables are the same in all my classes. I've added a NEW object, so I expect it to add a new object, right?
This is my code in my for loop. The print says that every variable in the object[i] has the same number.
ArrayList treeDots;
ArrayList branchList;
boolean clicked;
void setup ()
{
size(1024, 768, P3D);
clicked = false;
treeDots = new ArrayList();
branchList = new ArrayList();
treeDots.add(new TreeDot(width/2, height/2));
}
void draw ()
{
if (clicked)
AddTreeDot();
if (treeDots.size() > 1)
{
for (int i = 0; i < treeDots.size() -1 ; i++)
{
int temp_loc = 0;
TreeDot index1 = (TreeDot)treeDots.get(i);
TreeDot index2 = (TreeDot)treeDots.get(i + 1);
print(index1.xLoc(temp_loc) + " ");
print(i + " ");
print(index2.xLoc(temp_loc) + " ");
print(i + " ");
strokeWeight(2);
stroke(#09FF00);
line(index1.xLoc(temp_loc),index1.yLoc(temp_loc), index2.xLoc(temp_loc), index2.yLoc(temp_loc));
}
}
}
void AddTreeDot ()
{
int randomX = 0;
int randomY = 0;
treeDots.add(new TreeDot(randomDotX(randomX), randomDotY(randomY)));
clicked = false;
}
int randomDotX (int _randomX)
{
TreeDot temp = (TreeDot) treeDots.get(treeDots.size() -1);
int temp_x_loc = 0;
int lastDotX = temp.xLoc(temp_x_loc);
_randomX = lastDotX + int(random(-10, 10));
return _randomX;
}
int randomDotY (int _randomY)
{
TreeDot temp = (TreeDot) treeDots.get(treeDots.size() -1);
int temp_y_loc = 0;
int lastDotY = temp.yLoc(temp_y_loc);
_randomY = lastDotY + int(random(0, 10));
return _randomY;
}
void mouseClicked ()
{
clicked = true;
}
and here is my class code
int randomSpread;
boolean canIGrow;
boolean endDot;
int x_loc;
int y_loc;
int lineThickness;
class TreeDot
{
TreeDot (int x_loc_par, int y_loc_par)
{
x_loc = x_loc_par;
y_loc = y_loc_par;
//ellipse(x_loc_par, y_loc_par, 10, 10);
endDot = false;
}
int xLoc (int _x_loc)
{
_x_loc = x_loc;
return _x_loc;
}
int yLoc(int _y_loc)
{
_y_loc = y_loc;
return _y_loc;
}
}
The problem that you have to declare variable inside the class & this code will be prblematic.
int xLoc(int _x_loc)
{
_x_loc = x_loc;
return _x_loc;
}
int yLoc(int _y_loc)
{
_y_loc = y_loc;
return _y_loc;
}
Then in call it
int temp_loc = 0;
TreeDot index1 = (TreeDot)treeDots.get(i);
TreeDot index2 = (TreeDot)treeDots.get(i + 1);
print(index1.xLoc(temp_loc) + " ");
print(i + " ");
print(index2.xLoc(temp_loc) + " ");
print(i + " ");
This line index1.xLoc(temp_loc) reset the value for you to 0.
Your TreeDot getters/setters are messed up. In xLoc() you are passing in _x_loc, making it equal to x_loc and return it. Same for yLoc()
Class variables should be declared inside the class.
What you're doing is you're setting the same (global) variables each time you add a new TreeDot.
P.S. your getters are not the problem as some of the answers are mentioning.

Categories

Resources