Transferring a changed value from one method to another - java

so what I am trying to do it take the Value that I am allowing my BargainCustomer to spend, and get him/her to buy the first car they see in the list under that price. Then take the remaining money and buy whatever features they can. However, I do not remember how to call my value for the remaining money from my other method. Here is my code:
import java.util.ArrayList;
public class BargainCustomer implements Customer
{
public Car purchase(ArrayList<Car> listOfCars)
{
int moneyToSpend = 35000;
int moneyLeft = 0;
int indexLocation = 0;
for (int i = 0; i < listOfCars.size(); i++)
{
if (listOfCars.get(i).getBasePrice()<moneyToSpend)
{
moneyLeft=moneyToSpend-listOfCars.get(i).getBasePrice();
indexLocation = i;
}
}
return listOfCars.get(indexLocation);
}
public void upgrade(Car g)
{
int featuresMoney = moneyLeft;
for (int i = 0; i < g.getFeatures().size(); i++)
{
moneyLeft-=g.getFeatures().get(i).getCost();
if (moneyLeft>=0)
{
g.getFeatures().get(i).purchase();
}
}
}
}
Ideally the buyer should only buy what they can afford with the remaining money.

depending on your logic, it would be best to just chain the calls:
import java.util.ArrayList;
public class BargainCustomer implements Customer
{
public Car purchase(ArrayList<Car> listOfCars)
{
int moneyToSpend = 35000;
int moneyLeft = 0;
int indexLocation = 0;
for (int i = 0; i < listOfCars.size(); i++)
{
if (listOfCars.get(i).getBasePrice()<moneyToSpend)
{
moneyLeft=moneyToSpend-listOfCars.get(i).getBasePrice();
indexLocation = i;
}
}
return upgrade(listOfCars.get(indexLocation), moneyLeft);
}
public void upgrade(Car g, int moneyLeft)
{
int featuresMoney = moneyLeft;
for (int i = 0; i < g.getFeatures().size(); i++)
{
moneyLeft-=g.getFeatures().get(i).getCost();
if (moneyLeft>=0)
{
g.getFeatures().get(i).purchase();
}
}
}
}
This will just give you the car with all the features right away, if you need steps in between, you can just use a class variable, or calculate it again. Since you return the car, you can just substract the car price from the moneyToSpend
P.S. are you sure, int is the right choose for money in your case ? it will not handle comma values. Depending on currency, prices are rarly ever without fractions.

Related

How do I fix my For loop and Random problem in Android?

PlayerData class
public class PlayerData{
int id; // id means Player's order
boolean isTeacher;
public PlayerData() {
}
public void setID(int id) {
this.id = id;
}
public void setTeacher() {
isTeacher = true;
}
}
Singleton class
public class Singleton {
public int time;
public int total; // number of total players
public int teacher; // number of teachers
public int student; // number of students
public int count = 1;
public String keyWord; //
ArrayList<PlayerData> playerArrayList = new ArrayList<PlayerData>();
// method init creates Objects of players
public void init() {
for (int i = 1; i <= total; i++) {
PlayerData player = new PlayerData();
player.setID(i); // set id
playerArrayList.add(player); // add player Object to ArrayList
}
}
public void JobSelection() {
int a[] = new int[teacher]; // Make array to the number I will select
Random r = new Random(); // Random Object
PlayerData player = new PlayerData();
for (int i = 0; i < teacher; i++) // for loop to select Teachers
{
a[i] = r.nextInt(total) + 1; //select a number from 1~total and Save in a[0]~a[total]
for (int j = 0; j < i; j++) //for loop to avoid overlap
{
if (a[i] == a[j]) {
i--;
}
}
if (a[i] == player.id) {
playerArrayList.get(player.id - 1).isTeacher = true;
}
}
}
RoleSelection class
public class RoleSelection extends AppCompatActivity {
Singleton s1 = Singleton.getInstance();
PlayerData player = new PlayerData();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_role_selection07_03);
TextView t1 = (TextView) findViewById(R.id.textJobConfirm);
if (s1.playerArrayList.get(s1.player.id-1).isTeacher == true) {
t1.setText(" You job is Teacher ");
} else {
t1.setText(" Your job is Student ");
I am making an app game whose job consists of only Teacher and Student.
Codes above shows my app.
There is a player class that has its data and setters
There is a Singleton class that saves values in a variable such as total(total players), teacher, student etc..
Also Singleton class has ArrayList that creates Player's Objects.
In Singleton class I made 2 methods: One for creating Objects in a ArrayList, the other for giving objects their jobs.
JobSelection Method is trying to give a job to each player. For example if the total player chosen at game setting is 10 and teacher chosen is 4, I have to give 4 teacher jobs randomly to 10 player objects.
After giving the players a job, I wrote code in 'Role Selection' class to setText differently considering player's job.
I don't have any errors in my logcat or in my app.
However, I am only receiving "Your Job is Student". I guess the JobSelection method haven't worked well.
So I tried to fix these codes
for (int i = 0; i < teacher; i++) // for loop to select Teachers
{
a[i] = r.nextInt(total) + 1; //select a number from 1~total and Save in a[0]~a[total]
for (int j = 0; j < i; j++) //for loop to avoid overlap
{
if (a[i] == a[j]) {
i--;
}
}
if (a[i] == player.id) {
playerArrayList.get(player.id - 1).isTeacher = true;
}
}
But I failed to solve these problems...
I will be grateful if someone answers me how can I make jobs distributed and see different TextView according to their jobs. Thank you
I solved the problem by these codes:
for (int i = 0; i < teacher; i++)
{
a[i] = r.nextInt(total) + 1;
for (int j = 0; j < i; j++)
{
if (a[i] == a[j]) {
i--;
}
}
if (playerArrayList.get(a[i] - 1).id == a[i]) {
playerArrayList.get(a[i] - 1).setTeacher();
}
}
}

== null Doesn't work java

I have made a function for objects to reserve seats in a area. But if 2 objects enter the function at the same time they get the same seats. How do I solve this?
The Function getFreeChairs, returns the chair positions. And sets the Fan. But if two fans enter it at the same time they both get the same seats.
Sven
package model;
import actors.Fan;
import java.util.ArrayList;
import java.util.List;
/**
* Created by sveno on 12-10-2016.
*/
public class Vak {
private static int autoId = 1;
private String naam;
private int rijen, stoelenperrij, id;
private List<ArrayList> rows = new ArrayList<>();
private Fan fan = null;
public Vak(String naam, int rijen, int stoelenperrij) {
this.naam = naam;
this.rijen = rijen;
this.stoelenperrij = stoelenperrij;
this.id = autoId;
autoId++;
for (int i = 0; i < rijen; i++) {
rows.add(new ArrayList<Fan>());
}
for (ArrayList row : rows) {
for (int j = 0; j < stoelenperrij; j++) {
row.add(fan);
}
}
}
public void removeReserved(int rij, List<Integer> stoelen){
for (int i = 0; i < stoelen.size()-1; i++) {
//De reserveer alle stoelen
ArrayList<Fan> stoel = rows.get(rij);
stoel.set(stoelen.get(i),fan);
}
}
public int getRijen() {
return rijen;
}
public int getStoelenperrij() {
return stoelenperrij;
}
public List<ArrayList> getRows() {
return rows;
}
public int[] getFreeChairs(int aantalStoelen, Fan fan){
//Check for free seats
int count = 1;
int[] stoelenleeg = new int[aantalStoelen+1];
for (int j = 0; j < rows.size(); j++) {
for (int k = 0; k < rows.get(j).size(); k++) {
if (rows.get(j).get(k) == null){
stoelenleeg[count-1] = k;
count++;
//Not enough seats next to each other
if(count==aantalStoelen+1){
stoelenleeg[aantalStoelen] = j+1;
for (int o = 0; o < stoelenleeg.length-1; o++) {
ArrayList<Fan> stoel = rows.get(j);
stoel.set(stoelenleeg[o],fan);
}
return stoelenleeg;
}
}else{
//Not enough seats
stoelenleeg = new int[aantalStoelen+1];
count=1;
}
}
}
return stoelenleeg;
}
}
If your code is used in a concurrent context (multiple threads), you need to make sure that your code is thread safe.
It means that, only one single thread(person) should be able to call the getFreeChairs function(reserve a seat at a time)
The easy way to do it in java is to use the synchronized key word in the method definition:
public synchronized int[] getFreeChairs(int aantalStoelen, Fan fan){
...
}

How can I sort to associated arrays by using the elements of one of them only?

The task was to create a program which organises a users name with their corresponding mark and displays this in descending order. I'm asking how to sort both arrays at the same time but only by comparing the elements of one of the arrays. As a restriction, I cannot use classes, only associated arrays.
int [] ArrMarks = new int [5];
String [] ArrNames = new String [5];
Button to Accept user input
for (int i = 0; i < 5; i++)
{
ArrNames[i] = JOptionPane.showInputDialog("Enter a Name:");
ArrMarks[i] = Integer.parseInt(JOptionPane.showInputDialog("Enter a mark:"));
}
Display button including the part which sorts the code, this is the main part I am unsure of.
int Hi = ArrMarks[0];
for(int i = 0; i < 5; i++) {
if(ArrMarks[i] > Hi) {
Hi = ArrMarks[i];
}
}
txaDisplay.append("Names:"+"\t\t"+"Marks");
for (int i = 0; i < 5; i++) {
txaDisplay.append(ArrNames[i]+"\t\t"+ArrMarks[i]+"\n");
}
First of all, I would like to give a suggestion. Use lists instead of arrays. This kind of coding is not a good conventional way of coding. I will show a conventional way to handle the issue. You may take this if you like.
Create another class Mark.java with the following content
class Mark {
Integer mark;
String name;
public Integer getMark() {
return this.mark
}
public void setMark(Integer mark) {
this.mark = mark
}
public String getName() {
return this.name
}
public void setName(String name) {
this.name = name
}
}
Then in your current class create a List of this class.
List<Mark> marks = new ArrayList<Mark>();
Then after reading content from the user, you can add them to the list like following
for (int i = 0; i < 5; i++)
{
Mark mark = new Mark();
String name = JOptionPane.showInputDialog("Name:");
Integer mark = Integer.parseInt(JOptionPane.showInputDialog("Mark:"));
marks.add(mark)
}
Write a comparator class named MarkComparator.java. It deals with the sorting part.
public class MarkComparator implements Comparator<Mark> {
#Override
public int compare(Mark m1, Mark m2) {
return m1.getMark().compareTo(m2.getMark());
}
}
The use
Collections.sort(marks, new MarkComparator());
Now the List<Mark> of marks will be sorted.
You may then view the list the same way.
txaDisplay.append("Names:"+"\t\t"+"Marks");
for (Mark mark : marks)
{
txaDisplay.append(mark.getName()+"\t\t"+mark.getMark()+"\n");
}
The solution to my question required using a sorting technique to sort the names and marks, so that the program prints the corresponding mark to the name.
for(int i = 0; i < 5-1; i ++)
{
for(int j = i +1; j < 5; j++)
{
if (ArrMarks[i] < ArrMarks[j])
{
//sorting the names
String temp = ArrNames[i];
ArrNames[i] = ArrNames[j];
ArrNames[j] = temp;
//sorting the marks
int temp1 = ArrMarks[i];
ArrMarks[i] = ArrMarks[j];
ArrMarks[j] = temp1;
}
}
txaDisplay.append("Names:"+"\t\t"+"Marks"+"\n");
txaDisplay.append(ArrNames[i]+"\t\t"+ArrMarks[i]+"\n");
}

Algorithm course: Output of int sort and method to sort Strings

My assignment asks me to make a TV show program, where I can input shows, delete, modify and sort them. What I'm stuck on is the sorting part. With the show, it asks for the name, day a new episode premieres, and time. Those are the keys I need to sort it by.
The program prompts the user to input one of those keys, then the program needs to sort (sorting by day will sort alphabetically).
I made a class and used an array. Here is the class:
public class showInfo
{
String name;
String day;
int time;
}
And the method to sort by time in the code:
public static void intSort()
{
int min;
for (int i = 0; i < arr.length; i++)
{
// Assume first element is min
min = i;
for (int j = i+1; j < arr.length; j++)
{
if (arr[j].time < arr[min].time)
{
min = j;
}
}
if (min != i)
{
int temp = arr[i].time;
arr[i].time = arr[min].time;
arr[min].time = temp;
}
}
System.out.println("TV Shows by Time");
for(int i = 0; i < arr.length; i++)
{
System.out.println(arr[i].name + " - " + arr[i].day + " - " + arr[i].time + " hours");
}
}
When I call it and output it in the main, it only shows "TV Shows by Time" and not the list. Why is this?
Also, I need to make ONE method that I will be able to use to sort both the day AND the name (both Strings). How can I do this without using those specific arrays (arr[i].name, arr[i].day) in the method?
Any help would be greatly appreciated! Thanks in advance!
In this part of your code
if (min != i) {
int temp = arr[i].time;
arr[i].time = arr[min].time;
arr[min].time = temp;
}
You're just changing the time when you should move the whole object instead. To fix it, the code must behave like this:
if (min != i) {
//saving the object reference from arr[i] in a temp variable
showInfo temp = arr[i];
//swapping the elements
arr[i] = arr[min];
arr[min] = temp;
}
I̶t̶ ̶w̶o̶u̶l̶d̶ ̶b̶e̶ ̶b̶e̶t̶t̶e̶r̶ ̶t̶o̶ ̶u̶s̶e̶ ̶ Arrays#sort ̶w̶h̶e̶r̶e̶ ̶y̶o̶u̶ ̶p̶r̶o̶v̶i̶d̶e̶ ̶a̶ ̶c̶u̶s̶t̶o̶m̶ ̶̶C̶o̶m̶p̶a̶r̶a̶t̶o̶r̶̶ ̶o̶f̶ ̶t̶h̶e̶ ̶c̶l̶a̶s̶s̶ ̶b̶e̶i̶n̶g̶ ̶s̶o̶r̶t̶e̶d̶ ̶(̶i̶f̶ ̶y̶o̶u̶ ̶a̶r̶e̶ ̶a̶l̶l̶o̶w̶e̶d̶ ̶t̶o̶ ̶u̶s̶e̶ ̶t̶h̶i̶s̶ ̶a̶p̶p̶r̶o̶a̶c̶h̶)̶.̶ ̶S̶h̶o̶r̶t̶ ̶e̶x̶a̶m̶p̶l̶e̶:̶
showInfo[] showInfoArray = ...
//your array declared and filled with data
//sorting the array
Arrays.sort(showInfoArray, new Comparator<showInfo>() {
#Override
public int compare(showInfo showInfo1, showInfo showInfo2) {
//write the comparison logic
//basic implementation
if (showInfo1.getTime() == showInfo2.getTime()) {
return showInfo1.getName().compareTo(showInfo2.getName());
}
return Integer.compare(showInfo1.getTime(), showInfo2.getTime());
}
});
//showInfoArray will be sorted...
Since you have to use a custom made sorting algorithm and support different ways to sort the data, then you just have to change the way you compare your data. This mean, in your current code, change this part
if (arr[j].time < arr[min].time) {
min = j;
}
To something more generic like
if (compare(arr[j], arr[min]) < 0) {
min = j;
}
Where you only need to change the implementation of the compare method by the one you need. Still, it will be too complex to create and maintain a method that can support different ways to compare the data. So the best option seems to be a Comparator<showInfo>, making your code look like this:
if (showInfoComparator.compare(arr[j], arr[min]) < 0) {
min = j;
}
where the showInfoComparator holds the logic to compare the elements. Now your intSort would become into something more generic:
public static void genericSort(Comparator<showInfo> showInfoComparator) {
//your current implementation with few modifications
//...
//using the comparator to find the minimum element
if (showInfoComparator.compare(arr[j], arr[min]) < 0) {
min = j;
}
//...
//swapping the elements directly in the array instead of swapping part of the data
if (min != i) {
int temp = arr[i].time;
arr[i].time = arr[min].time;
arr[min].time = temp;
}
//...
}
Now, you just have to write a set of Comparator<showInfo> implementations that supports your custom criteria. For example, here's one that compares showInfo instances using the time field:
public class ShowInfoTimeComparator implements Comparator<showInfo> {
#Override
public int compare(showInfo showInfo1, showInfo showInfo2) {
//write the comparison logic
return Integer.compare(showInfo1.getTime(), showInfo2.getTime());
}
}
Another comparator that uses the name field:
public class ShowInfoNameComparator implements Comparator<showInfo> {
#Override
public int compare(showInfo showInfo1, showInfo showInfo2) {
//write the comparison logic
return showInfo1.getName().compareTo(showInfo2.getName());
}
}
Now in your code you can call it like this1:
if (*compare by time*) {
genericSort(showInfoArray, new ShowInfoTimeComparator());
}
if (*compare by name*) {
genericSort(showInfoArray, new ShowInfoNameComparator());
}
if (*another custom rule*) {
genericSort(showInfoArray, new ShowInfoAnotherCustomRuleComparator());
}
where now you can implement a custom rule like compare showInfo objects using two or more fields. Taking as example your name and day fields (as stated in the question):
public class ShowInfoNameAndDayComparator implements Comparator<showInfo> {
#Override
public int compare(showInfo showInfo1, showInfo showInfo2) {
//write the comparison logic
int nameComparisonResult = showInfo1.getName().compareTo(showInfo2.getName());
if (nameComparisonResult == 0) {
return showInfo1.getDay().compareTo(showInfo2.getDay());
}
return nameComparisonResult;
}
}
1: There are other ways to solve this instead using lot of if statements, but looks like that's outside the question scope. If not, edit the question and add it to show another ways to solve this.
Other tips for your current code:
Declare the names of the classes using CamelCase, where the first letter of the class name is Upper Case, so your showInfo class must be renamed to ShowInfo.
To access to the fields of a class, use proper getters and setters instead of marking the fields as public or leaving the with default scope. This mean, your ShowInfo class should become into:
public class ShowInfo {
private String name;
private String day;
private int time;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
//similar for other fields in the class
}
Use selection sort algorithm which is easy to implement,
for (int i = 0; i < arr.length; i++)
{
for (int j = i + 1; j < arr.length; j++)
{
if (arr[i].time > arr[j].time) // Here ur code that which should be compare
{
ShowInfo temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
no need to check min element. go through this wiki http://en.wikipedia.org/wiki/Selection_sort
Why not you use a Collection for this sort of a thingy to work. Moreover, in your added example, you are simply changing one attribute of a given object, while sorting, though you not changing the position of the object as a whole, inside the given list.
Create a List which will contain the references of all the Shows, now compare each attribute of one Show with another, in the List. Once the algorithm feels like, that swapping needs to be done, simply pick the reference from the List, save it in a temp variable, replace it with a new reference at this location, and set duplicate to the one stored in the temp variable. You are done, List is sorted :-)
Here is one small example for the same, for help :
import java.io.*;
import java.util.*;
public class Sorter {
private BufferedReader input;
private List<ShowInfo> showList;
public Sorter() {
showList = new ArrayList<ShowInfo>();
input = new BufferedReader(
new InputStreamReader((System.in)));
}
private void createList() throws IOException {
for (int i = 0; i < 5; i++) {
System.out.format("Enter Show Name :");
String name = input.readLine();
System.out.format("Enter Time of the Show : ");
int time = Integer.parseInt(input.readLine());
ShowInfo show = new ShowInfo(name, time);
showList.add(show);
}
}
private void performTask() {
try {
createList();
} catch (Exception e) {
e.printStackTrace();
}
sortByTime(showList);
}
private void sortByTime(List<ShowInfo> showList) {
int min;
for (int i = 0; i < showList.size(); i++) {
// Assume first element is min
min = i;
for (int j = i+1; j < showList.size(); j++) {
if (showList.get(j).getTime() <
showList.get(min).getTime()) {
min = j;
}
}
if (min != i) {
ShowInfo temp = showList.get(i);
showList.set(i, showList.get(min));
showList.set(min, temp);
}
}
System.out.println("TV Shows by Time");
for(int i = 0; i < showList.size(); i++) {
System.out.println(showList.get(i).getName() +
" - " + showList.get(i).getTime());
}
}
public static void main(String[] args) {
new Sorter().performTask();
}
}
class ShowInfo {
private String name;
int time;
public ShowInfo(String n, int t) {
name = n;
time = t;
}
public String getName() {
return name;
}
public int getTime() {
return time;
}
}
EDIT 2 :
For sorting By Name you can use this function :
private void sortByName(List<ShowInfo> showList) {
int min;
for (int i = 0; i < showList.size(); i++) {
// Assume first element is min
min = i;
for (int j = i+1; j < showList.size(); j++) {
int value = (showList.get(j).getName()).compareToIgnoreCase(
showList.get(min).getName());
if (value < 0)
min = j;
}
if (min != i) {
ShowInfo temp = showList.get(i);
showList.set(i, showList.get(min));
showList.set(min, temp);
}
}
System.out.println("TV Shows by Time");
for(int i = 0; i < showList.size(); i++) {
System.out.println(showList.get(i).getName() +
" - " + showList.get(i).getTime());
}
}
EDIT 3 :
Added Comparable<?> Interface, to the existing class to perform sorting based on specified input. Though one can improve on the logic, by using Enumeration, though leaving it for the OP to try his/her hands on :-)
import java.io.*;
import java.util.*;
public class Sorter {
private BufferedReader input;
private List<ShowInfo> showList;
private int command;
public Sorter() {
showList = new ArrayList<ShowInfo>();
input = new BufferedReader(
new InputStreamReader((System.in)));
command = -1;
}
private void createList() throws IOException {
for (int i = 0; i < 5; i++) {
System.out.format("Enter Show Name :");
String name = input.readLine();
System.out.format("Enter Time of the Show : ");
int time = Integer.parseInt(input.readLine());
ShowInfo show = new ShowInfo(name, time);
showList.add(show);
}
}
private void performTask() {
try {
createList();
} catch (Exception e) {
e.printStackTrace();
}
System.out.format("How would you like to sort : %n");
System.out.format("Press 0 : By Name%n");
System.out.format("Press 1 : By Time%n");
try {
command = Integer.parseInt(input.readLine());
} catch (Exception e) {
e.printStackTrace();
}
sortList(showList);
}
private void sortList(List<ShowInfo> showList) {
int min;
for (int i = 0; i < showList.size(); i++) {
// Assume first element is min
min = i;
for (int j = i+1; j < showList.size(); j++) {
showList.get(j).setValues(command);
int value = showList.get(j).compareTo(showList.get(min));
if (value < 0) {
min = j;
}
}
if (min != i) {
Collections.swap(showList, i, min);
}
}
System.out.println("TV Shows by Time");
for(int i = 0; i < showList.size(); i++) {
System.out.println(showList.get(i).getName() +
" - " + showList.get(i).getTime());
}
}
public static void main(String[] args) {
new Sorter().performTask();
}
}
class ShowInfo implements Comparable<ShowInfo> {
private String name;
private int time;
private int command;
public ShowInfo(String n, int t) {
name = n;
time = t;
}
public String getName() {
return name;
}
public int getTime() {
return time;
}
public void setValues(int cmd) {
command = cmd;
}
public int compareTo(ShowInfo show) {
int lastCmp = 1;
if (command == 0) {
lastCmp = name.compareTo(show.name);
} else if (command == 1) {
if (time < show.time) {
lastCmp = -1;
} else if (time == show.time) {
lastCmp = 0;
} else if (time > show.time) {
lastCmp = 1;
}
}
return lastCmp;
}
}

Beginner: Assigning values to arrays in Java

I am attempting to write a simple Genetic Algorithm in Java after reading a book on Machine Learning and have stumbled on the basics. I'm out of practice with Java so I'm probably missing something extremely simple.
Individual
public class Individual {
int n;
int[] genes = new int[500];
int fitnessValue;
public int getFitnessValue() {
return fitnessValue;
}
public void setFitnessValue(int fitnessValue) {
this.fitnessValue = fitnessValue;
}
public int[] getGenes() {
return genes;
}
public void setGenes(int index, int gene) {
this.genes[index] = gene;
}
public int getN() {
return n;
}
public void setN(int n) {
this.n = n;
}
// Constructor
public Individual() {
}
}
Population
import java.util.Random;
public class Population {
public Population() {
}
public static void main(String[] args) {
Random rand = new Random();
int p = rand.nextInt(10);
int n = rand.nextInt(10);
Individual pop[] = new Individual[p];
System.out.println("P is: " + p + "\nN is: " + n);
for(int j = 0; j <= p; j++) {
for(int i = 0; i <= n; i++) {
pop[j].genes[i] = rand.nextInt(2);
}
}
}
public void addPopulation() {
}
}
The aim of this code is to populate the Population and the Genes with a random number. Could someone please take a look at my code to see where I'm going wrong?
before
pop[j].genes[i] = rand.nextInt(2);
add
pop[j] = new Individual();
the elements of the array are null.
I believe you need to initialize pop[j] before doing pop[j].genes[i] = rand.nextInt();
Individual pop[] = new Individual[p];
This just initializes the array, not the individual elements. Try to put pop[j] = new Individual() between your two loops.
What they said...
Also, do you mean to call your setGenes method, or do you just want to directly access the gene array.
From what I understand of your code I think you need to do this:
for(int j = 0; j <= p; j++) {
pop[j] = new Individual();
for(int i = 0; i <= n; i++) {
pop[j].setGenes(i, rand.nextInt(2));
}
}

Categories