The code is :
package classes;
public class Test {
private static double mutationRate = 0.5;
public static void main(String[] args) {
Population pop = new Population();
pop.initialise();
Population po = new Population();
po.getIndividusList().add(pop.getFittest());
po.getIndividusList().add(mutate(pop.getIndividusList().get(1)));
}
private static Chromosom mutate(Chromosom l) { // changer les couples d'interventions des parcs)
// loop through genes
Chromosom ch = new Chromosom();
for (int i = 0; i < l.size(); i++)
ch.put(i, l.get(i));
for (int i = 0; i < ch.size(); i++) {
double alea = Math.random() * 13;
int moisIntervention1 = (int) alea;
Intervention interv1 = new Intervention(1, moisIntervention1);
ch.get(i).modInterventions(ch.get(i).intervention2(interv1));
}
return ch;
}
}
The problem is that I did not change the instance pop but when I change the other instance po, pop changes too.
java pass by value.
when you call this mutate(pop.getIndividusList().get(1))
you are sending pop's instance, so it will get change.
Supose pop.getIndividusList().get(1) return String varibale do this way
String var=pop.getIndividusList().get(1);
then call mutate(var)
I'm unsure about whether I understood the problem, but I think that you mean that when you alter the items in Population po, the items in Population pop mirror those changes.
That is, indeed, the expected behavior of your code: to populate po, you are adding items from pop - (pop.getFittest, pop.getList.get(1) ).
But the individuals are, I believe, instances of objects, so add/remove and similar operations work with references to the objects, and not with copies of them. Therefore, as you have 2 references to the same obj, any change is mirrored.
IF you want to create a copy, you should add to po a new object with the same state, either by creating a constructor that takes another instance as parameter, implementing a copy method, or something similar.
It should be something like this:
Population po = new Population();
Individual fittest = pop.getFittest();
Individual poCopy = new Individual();
//ADD CODE HERE TO COPY ALL THE FIELDS FROM fittest TO poCopy
//....
po.getIndividusList().add(poCopy);
Related
ArrayList<Integer> companiesId = new ArrayList<>();
int numberOfCompanies = 10; // Just for example
...
float profit;
Scanner input = new Scanner(System.in);
for(int i = 0; i < numberOfCompanies; i++) {
int companyId = input.nextInt();
if (!companiesId.contains(companyId)) {
companiesId.add(companyId);
}
if (companiesId.get(i) == 1) {
profit = 1000;
} else if (companiesId.get(i) == 2) {
profit = 2000;
}
}
Now I want to print all the companyIds from the ArrayList with the profit entered for each id, but I don't know how to do it with the ArrayList.
It should be:
1 1000
2 2000
...
You cannot do what you ask because part of the information you need to print (profit) is lost. What you need to do first is to create a class that holds a company ID and the profits. With the new version of Java, you can create a record that will hold such information. A Java Record is nothing more than a POJO that is identified with that new keyword (record) and does not require you to create all the boilerplate code. Your record class will look something like this:
public record CompanyRecord(int companyID, float profit) {
}
You don't even need to override toString(). That is, unless you want to print the contents of the record in a different way than the default. Then, you will need to create a list of CompanyRecord objects:
ArrayList<CompanyRecord> companies = new ArrayList<>();
Then, you can do whatever you need. For example, I created this simple demo that create a list of 10 company records and uses the loop counter to set the company ID and as a multiplier for the profits. Lastly, it prints out the record to the console.
public class CompanyRecordDemo {
public static void main(String[] args) {
ArrayList<CompanyRecord> companies = new ArrayList<>();
float profit = 1000.0f;
for (int i = 1; i <= 10; i++) {
CompanyRecord rec = new CompanyRecord(i, profit * i);
companies.add(rec);
System.out.println(rec);
}
// do whatever you need with the list...
}
}
The output of this small program is:
CompanyRecord[companyID=1, profit=1000.0]
CompanyRecord[companyID=2, profit=2000.0]
CompanyRecord[companyID=3, profit=3000.0]
CompanyRecord[companyID=4, profit=4000.0]
CompanyRecord[companyID=5, profit=5000.0]
CompanyRecord[companyID=6, profit=6000.0]
CompanyRecord[companyID=7, profit=7000.0]
CompanyRecord[companyID=8, profit=8000.0]
CompanyRecord[companyID=9, profit=9000.0]
CompanyRecord[companyID=10, profit=10000.0]
This is probably the simplest way to accomplish what you need. You will need to use Java 14 or later to make use of Java Records, but I recommend you use the latest version.
UPDATE: One important thing to note is that Java records are immutable. So, they have no setters (mutator methods). You will have to set the values through the constructor and values cannot be changed afterwards. You can access (get) the property values by calling a method that has the same name as the field. For example, the getter method for profit is profit(). For example rec.profit().
I am creating a game in java. I am using an array of Armor's for equipment
The issue, is that whenever I change 1 variable in my array, the other objects are also affected. This looks like a pointer issue but, all of the objects have been initialized as separate and called as new.
private Armor[] equip = new Armor[3];
public Inventory()
{
for(int i = 0; i<3;i++)
equip[i] = new Armor();
equip[0] = new Armor("head","You don't have head equipment","head",0,10,0,0);
equip[1] = new Armor("tunic","A simple farmers tunic","chest",0,10,0,0);
equip[2] = new Armor("baggy pants","Basic pants woven from rough cloth","legs",0,10,0,0);
System.out.println(armorDes(0));
System.out.println(armorDes(1));
System.out.println(armorDes(2));
}
All of the print lines output
baggy pants
0 armor
10 evasion bonus
Basic pants woven from rough cloth
instead of their own stats.
This was tested with a debugger and all of the objects are declared to different locations in data. Is this a java issue are am I just stupid?
Code is unclear above
private Armor[] equip = new Armor[3];
public Inventory()
{
for(int i = 0; i<3;i++)
equip[i] = new Armor();// Why creating object using default constructor here? no use
equip[0] = new Armor("head","You don't have head equipment","head",0,10,0,0);
equip[1] = new Armor("tunic","A simple farmers tunic","chest",0,10,0,0);
equip[2] = new Armor("baggy pants","Basic pants woven from rough cloth","legs",0,10,0,0);
// Use toString() method in Armour class to see the values present in variables.
//Also be sure all variables are instance variables
System.out.println(equip[0]);
System.out.println(equip[1]);
System.out.println(equip[2]);
//System.out.println(armorDes(0));
//System.out.println(armorDes(1));
//System.out.println(armorDes(2));
}
I have a sequence of information being randomly generated. I would like to save that information in a variable of some kind so that it can be recalled elsewhere. i think I want to use an ArrayList, but I'm not sure how to add the information while inside a for loop (which is where it is being created). The code I have is as follows:
public static ArrayList<String> phoneList
public static void main(String[] args){
Random randomNumber = new Random();
int howMany = randomNumber.nextInt(11);;
String holding;
for (int i=0; i < howMany; i++){
int itemRandNum = randomNumber.nextInt(11);//for all Item Categories
int priceRandNum = randomNumber.nextInt(11);//Prices for all categories
holding = phones[itemRandNum]+" $"+ priceOfPhones[priceRandNum];
//System.out.println(holding);
phoneList.add("holding"); //here is where I would like to add the information
//contained in "holding" to the "phoneList" ArrayList.
}
System.out.println(phoneList);
}
I am getting a NullPointerException. If an ArrayList is not the best thing to use here, what would be?
Any help you can give is appreciated.
public static void String Main(String[] args) suggests this doesn't have much to do with Android.
First, instantiate the list (Outside your for loop):
phoneList = new ArrayList<>(howMany); //Adding "howMany" is optional. It just sets the List's initial size.
Then, add the values:
for (int i = 0; i < howMany; i++) {
//...
phoneList.add(holding);
//Don't place holding in quotation marks, else you'll just add "holding" for every entry!
}
You get a NullPointerException because ArrayList phoneList is null since you didn't initialize it. Therefore write
public static ArrayList<String> phoneList = new ArrayList<>();
As it is you are just declaring the class ArrayList not instantiating it. it is necessary for all the time you want to use a class to create an instance of the same class and thats simple, just do:
public static ArrayList phoneList = new ArrayList() (if you are running older versions of java), otherwise use public static ArrayList phoneList = new ArrayList<>().
Ok so I'm doing an assignment for my java coursets part I'm stuck at is :
"Implement an operation createparliamentMembers which will create the particular Parliament
with 80 members."
So i've already created the constructor with it's methods. This is how I wrote the operation to create the objects using the constructor.:
public static void createparliamentMembers(){
Member[] array = new Member[75];
for(int i = 0; i < array.length; i++)
{
if (i < 35) array[i] = new Member(i, "Blue");
else array[i] = new Member(i,"Red");
}
Legislator[] leg = new Legislator[3];
for (int i = 0 ; i < leg.length; i++){
leg[i] = new Legislator(i, "Impartial");
}
Leader[] lead = new Leader[2];
for (int t = 0; t < lead.length; t++){
if (t < 1) lead[t] = new Leader(1, "Red");
else lead[t] = new Leader(2, "Blue");
}
The problem is the arrays and objects only seem to exist in the operation for creating them and when I try running method of the objects created they don't work because the driver class doesn't recognize the arrays. On the other hand when I use this as just a normal part of the Driver for it runs fine and all methods of the objects work normally.
Edit: Ok so I'm still getting the same problem as before even though i initiliased them outside the createparliamentMembers();
The following code is the Driver im using to test the methods: It keeps saying there is a:
Exception in thread "main" java.lang.NullPointerException at Driver.main(Driver.java:11)
which is the code array[1].FlipCoin(); as im trying to use the method flipcoin from the created objects but it's not working.
public static void main(String [] args) {
Commands.createparliamentMembers();
array[1].FlipCoin();
}
Your arrays are only defined locally, which means they live and die with the method. When your method finishes, they get put out of memory.
The solution is to define these arrays as instance variables. By that I mean, you need to define the arrays for your class, and then use them in your method:
class someClass {
int[] myArray = new int[2];
private void someMethod() {
myArray[0] = 3;
myArray[1] = //whatever
}
}
You state in comment:
I do have a parliament class it's on it own and contains the methods and constructor for the members of the parliament. The above method was in a seprate class called Commands. I don't understand completely the "Can you add the members to a Parliament object as you create them?" The parliament isn't an object more se then a class containing a constructor and methods for parliament members i want to create.
Parliament isn't an object yet, but you should in fact create one, and in fact your instructions tell you just that: "which will create the particular Parliament with 80 members...". You will need to tell us more about your program's structure and your specific requirements, but I suggest:
First create a Parliament object in the createParliamentMembers method, and call it parliament.
Then create the members of parliament in that method.
As you create these members, add them to the Parliament object, parliament.
At the end of the method return the parliament variable.
This means that your createParliamentMembers method's signature must change so that rather than return void it should be written to return a Parliament object.
When calling the method in the main method, assign what it returns to a Parliament variable that is in the main method.
It looks like you are writing a factory method. Create a constructor for Parliament like this:
public Parliament(Member[] members, Legislator[] legislators, Leader[] leaders) {
// do whatever with what's passed in
}
Then change your method to return a Parliament object and in the method pass your initialized arrays into the Parliament constructor, like this:
// same code as your except the last line
public static Parliament createParliament(){
Member[] array = new Member[75];
for(int i = 0; i < array.length; i++)
{
if (i < 35) array[i] = new Member(i, "Blue");
else array[i] = new Member(i,"Red");
}
Legislator[] leg = new Legislator[3];
for (int i = 0 ; i < leg.length; i++){
leg[i] = new Legislator(i, "Impartial");
}
Leader[] lead = new Leader[2];
for (int t = 0; t < lead.length; t++){
if (t < 1) lead[t] = new Leader(1, "Red");
else lead[t] = new Leader(2, "Blue");
}
return new Parliament(array, leg, lead);
}
I have a list of longitude and longitude points in an xml file that is used throughout my application. I find my self repeating this code to get points often and think there must be a better way?
String[] mTempArray = getResources().getStringArray(R.array.stations);
int len = mTempArray.length;
mStationArray = new ArrayList<Station>();
for(int i = 0; i < len; i++){
Station s = new Station();
String[] fields = mTempArray[i].split("[\t ]");
s.setValuesFromArray(fields);
Log.i("ADD STATION", ""+s);
mStationArray.add(s);
}
XML is in the format of:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<array name="stations">
<item>
<name>Station name</name>
<longitude>1111111</longitude>
<latitude>11111</latitude>
<code>1</code>
</item>
And another (possible) problem is that to get just one station I have to get all of them and pull the one I want from the array. Is this going to be considerably slower? Can I make this array consistent throughout the app? (But keeping the separate Intent methodology)
I had the same thought as MilkJug, to use a utility method to create the stations, but I want to offer a slightly different approach: Move as much of the construction logic as possible into the Station class constructor. To keep the example simple, I'm moving the utility method into the Station class as well.
This provides an overall cleaner design, as outside of the Station class itself, your code should never have to deal with a Station object whose construction/initialization steps haven't been fully completed.
(kgiannakakis's suggestion to use a database may be a better way to go if you have a lot of Station objects.)
public class Station {
private static List<Station> sStationArray = null;
/**
* Construct a Station from a specially-encoded String. The String
* must have all the necessary values for the Station, separated by tabs.
*/
public Station(String fieldString) {
String[] fields = fieldString.split("[\t ]");
// For safety, setValuesFromArray() should be declared 'final'.
// Better yet, you could just move its body into this constructor.
setValuesFromArray(fields);
// I'm assuming 'mName' is the name field for the Station
Log.i("Station", this.mName);
}
public static Station getStationArray(Context ctx) {
if (sStationArray == null) {
// (Please don't use the prefix 'm' for non-member variables!)
final String[] tempArray =
ctx.getResources().getStringArray(R.array.stations);
final int len = tempArray.length;
// Passing the length into the ArrayList constructor (if it's
// known, or can be guessed at) can be a very simple yet
// effective optimization. In this case the performance boost
// will almost certainly **not** be meaningful, but it's
// helpful to be aware of it.
sStationArray = new ArrayList<Station>(len);
for (int i = 0; i < len; i++) {
Station s = new Station(tempArray[i]);
sStationArray.add(s);
}
}
return sStationArray;
}
}
Why not create a utility method that takes a context as a parameter and returns the station resources? For example:
public class StatUtil {
private static List<Station> mStationArray = null;
public static Station getStation(Context ctx) {
if (mStationArray == null) {
String[] mTempArray = getResources().getStringArray(R.array.stations);
int len = mTempArray.length;
mStationArray = new ArrayList<Station>();
for(int i = 0; i < len; i++){
Station s = new Station();
String[] fields = mTempArray[i].split("[\t ]");
s.setValuesFromArray(fields);
Log.i("ADD STATION", ""+s);
mStationArray.add(s);
}
}
return mStationArray;
}
}
and call it from your code with:
stationArray = StatUtil.getStation(this);
Repeatedly fetching the stations will be slower than caching them, but not significantly slower unless you are fetching them in a loop. Doing as above will prevent multiple copies from being fetched.
I could propose two solutions:
You could create a Singleton class that initializes once, reads the data from the XML and stores the stations in a List or a Map. Use a Map if you want to quickly find a station based on its name. The Singleton class will provide methods for retrieving all stations or just one of them.
Create a database table and store the information there. You may need more code, but the advantage will be that you will be able to run more advanced queries.