Java array issue - java

How would I go about creating an array of say 5 items and then after create an array for each item?. I know how to create an array of 5 items but the problem I have is creating an array for each one after. Im assuming I would need 5 arrays since there's 5 items.
int gas = 0;
int food = 0;
int clothes = 0;
int entertainment = 0;
int electricity = 0;
int[] budget = new int[4];
budget[0] = gas;
budget[1] = food;
budget[2] = clothes;
budget[3] = entertainment;
budget[4] = electricity;
thanks in advance

Instead of creating a 2-dimensional array holding types of amounts that are logically grouped together (I assume per month) it would be better to define a data-holder class so that you can access the amounts using their name instead of an error-prone index.
For example (minus the getters and setters):
public class Budget {
public int gas = 0;
public int food = 0;
public int clothes = 0;
public int entertainment = 0;
public int electricity = 0;
};
// ....
Budget[] months = new Budget[12];
budget[0].gas = gasCosts;
budget[0].food = foodCosts;
// etc

Are you saying you want to create a 2D array? Each element in the budget array is another array?
You'd use a loop.
int[] budget = new int[5]; //There are 5 elements to be stored in budget, not 4
for (int y = 0; y < 5; y++) {
budget[y] = new int[5];
}

Maybe you need a matrix.
int[][] budget = new int[4][4];
In the first index you keep the budget and in the second index the five (in the case above) budget items.
When you have a matrix [x][y] you have x+1 arrays each of wich with y+1 elements.

There are 5 elements in the array.
int[] budget = new int[5];
budget[0] = gas;
budget[1] = food;
budget[2] = clothes;
budget[3] = entertainment;
budget[4] = electricity;
You need 2-dimensional array, which is basically an array of array. The 2D array is declared by 2 pairs of []. In the following example, each budget have 10 details.
String[][] detail = new String[budget.length][10];

If I'm understanding you correctly, you want a 2d array that would be something like ...
int gas = 0;
int food = 1;
int clothes = 2;
int entertainment = 3;
int electricity = 4;
int maxEntries = 10;
int[][] myArray = new int[5][maxEntries];
This could be accessed via:
myArray[gas][entryNumber] = 6;
int value = myArray[gas][entryNumber];
But how inflexible this is? You have to know in advance how many entries there will be for each "category" or have code that checks a given array length when you're adding an item, creating an new array when you need a larger one (and copying the old data into it).
What you probably want at the very least is a ArrayList of ArrayLists:
ArrayList<ArrayList<Integer>> my2dArrayList =
new ArrayList<ArrayList<Integer>>();
...
my2dArrayList.get(gas).add(someValue);
int myValue = my2dArrayList.get(gas).get(index);
Or a HashMap of ArrayLists you could access via the names of your categories:
HashMap<String, ArrayList<Integer>> myMap =
new HashMap<String, ArrayList<Integer>>();
...
myMap.get("gas").add(someValue);
int myValue = myMap.get("gas").get(index);

Related

List contain only two last objects when I try add different objects

I create new chromosomes and add to list(I'm sure that chromosomes are different because I've printed them before adding) but in the end when I print list or get random index there are only two last chromosomes.(Generally during interation I create two new chromosomes from two random chromosomes from current generation in order to create new generation through crossover).
public Population crossoverChromosomes(Population population, List<Item> items, int capacityOfKnapsack) {
Random rand = new Random();
List<Chromosome> chromosomeList = new ArrayList<>(population.getChromosomeList());
int genesLength = population.chromosomeList.get(0).getGenes().length;
int newGenes1[] = new int[genesLength];
int newGenes2[] = new int[genesLength];
ArrayList<Chromosome> newCrossoverPopulation = new ArrayList<>();
for (int j = 0; j < population.getPopulationSize() / 2; j++) {
int firstChrIndex = rand.nextInt(population.getPopulationSize() - 1);
int secondChrIndex = rand.nextInt(population.getPopulationSize() - 1);
int d = rand.nextInt(population.getPopulationSize() - 1);
Chromosome firstChr = chromosomeList.get(firstChrIndex);
Chromosome secondChr = chromosomeList.get(secondChrIndex);
for (int i = 0; i < genesLength; i++) {
if (i < d) {
newGenes1[i] = firstChr.getGenes()[i];
newGenes2[i] = secondChr.getGenes()[i];
} else {
newGenes1[i] = secondChr.getGenes()[i];
newGenes2[i] = firstChr.getGenes()[i];
}
}
Chromosome chr1 = new Chromosome(genesLength, newGenes1);
Chromosome chr2 = new Chromosome(genesLength, newGenes2);
chr1.fitnessCalculate(items, capacityOfKnapsack);
newCrossoverPopulation.add(chr1);
chr2.fitnessCalculate(items, capacityOfKnapsack);
newCrossoverPopulation.add(chr2);
}
return new Population(newCrossoverPopulation.size(), newCrossoverPopulation);
}
I've found problem, even if I use "new" operator during creating chromosomes, chr1 and chr2 and I add new chromosomes, finally every references refere only to chr1 or chr2 so to last two latest objects. Why it doesn't work? Maybe I should create new chromosomes this way list.add(new chr)? EDIT: it still doesn't work I have no idea why objects in list always refere to last two created chromosomes objects.
EDIT2: SOLVED(I've created table only before loop and even if my objects was a new reference, variable "genes" in chromosome was still the same table that I've created before loop)

Declaration of Array not accepted

I am creating a class that will play the role of a computer player in a virtual game of sticks. However, when I use the constructor method for this class, I lose the array that I have created, even though I had already declared the array in the state attributes. After 20 minutes, I am completely lost.
I am new to Java, and am trying to learn and get better. Any help would really be appreciated.
Below is the redesigned AI class along with the error that Eclipse keeps on submitting.
public class RedesignedAI {
private int[][] largeArray;
private int AIChoiceStick;
private Random random = new Random();
private int CurrentScore[] = new int[51]; //at max, if 100 sticks are initially chosen, then each player takes at max 50 sticks,
private int h = 0; //^so why not have one more in case
public RedesignedAI(int NumberSticks) //this is a constructor method and creates the arrays that contains a
{
largeArray[][] = new int[NumberSticks][3];
int i = 0;
while(i < NumberSticks)
{
largeArray[i][0] = 1; //ADD THIS
largeArray[i][1] = 1;
largeArray[i][2] = 1;
i++;
}
}
The error: largeArray cannot be resolved to a type.
You initialized the largeArraythe wrong way. Use:
largeArray = new int[NumberSticks][3];
That new allocate a 2D array, so types are coherent both sides of the =.
If you want to allocate chunk by chunk then you should use [] syntax:
largeArray = new int[NumberSticks][]; // array of NumberSticks entries to array of int (not yet determined)
for (int i=0; i<NumberSticks; i++) {
largeArray[i] = new int[3]; // i-th entry of array largeArray is a new array of 3 ints
}
largeArray is a reference to array of reference to array of ints. largeArray[i] is a reference to array of ints. largeArray[i][j]is an int.
Try this
private int[][] largeArray = null;
Initially initialize with null.
then in constructor
largeArray[][] = new int[3][3];
Since value is dynamic and you are changing it anyhow
You have to initialize the array on the top:
private int[][] largeArray = new int[x][y];
An array always has a fixed length. Only a list can variate the length.
Change this:
largeArray[][] = new int[NumberSticks][3];
into this:
largeArray = new int[NumberSticks][3];
Wrong Code:
largeArray[][] = new int[NumberSticks][3];
Instead use:
largeArray = new int[NumberSticks][3];
You don't need the [][] in the largeArray code of the constructor. This will do:
largeArray = new int[NumberSticks][3];
You may find it easier to use ArrayList instead. Maybe something like this:
private List<List<Integer>> largeArray;
...
public RedesignedAI(int NumberSticks) {
largeArray = new ArrayList<>();
int i = 0;
while(i < NumberSticks) {
List<Integer> innerArray = new ArrayList<>();
innerArray.add(1);
innerArray.add(1);
innerArray.add(1);
largeArray.add(innerArray);
i++;
}
}

Shuffle the Integer of the Object<Integer,String> in a List/ArrayList

List<Data> list = new ArrayList<Data>();
public class Data{
public int n;
public String p;
public Data(int N, String P) {
n = N;
p = P;
}
}
How can i shuffle the Integer of the Object: Data. So the String stays at the same position, and the Integer get's shuffled.
Loop through list and store the int of each Data object in a separate list. Shuffle this list using Collections.shuffle(...). Loop through this new shuffled list and set the n field of each corresponding member of list to the new random int found in the shuffled list.
Probably have to do it yourself:
for (int i = list.size(); i > 0; i--) {
int j = (int)(Math.random() * (i + 1));
int temp = list.get(i).n;
list.get(i).n = list.get(j).n;
list.get(j).n = temp;
}
The best you can do from java libraries is to first split it into two lists, one of ints and one of strings, then shuffle only the ints (using Collections.shuffle), then combine the two lists back into one list of Datas
You could use something like this:
List<Integer> ns = new ArrayList<Integer>(list.size());
for (Data data : list) {
ns.add(data.n);
}
Collections.shuffle(ns);
for (int i = 0; i < list.size(); i++) {
Data data = list.get(i);
int newN = ns.get(i);
data.n = newN;
}
Note that it's best practice to use accessors getN() and setN(int) and make Data.n private.

Java-Hibernate from List of values to multidimensional double arrays

With the following snippet I am trying to build from a List returned from Hibernate a multidimensional array , double[][]:
The data list gets to makeSet, the makeSet tries to return a [][] double array. The optimal, is that I don't know how many arrays should I have. So I tried calling makeInnerSet but unless I create a new double[][] ix, iy in the code, the code does not iterate well.
Is there a way to know the columns of an array [][] ?
Perhaps is there another approach to the problem ?
It's mandatory to take back the scalar values of Hibernate and make them double[][] of what ever size. Any help ?
List data = qry.list();
double[][] inputData = makeSet(data);
public double[] makeInnerSet(List data, double[] ix, int col ){
int i = 0;
Iterator<?> itr1 = data.listIterator();
while (itr1.hasNext()) {
Object[] result = (Object[]) itr1.next();
if (result[col] != null) {
double res1 = (Double) result[col];
ix[i] = res1;
}else{
ix[i] = 0;
}
i++;
}
return ix;
}
public double[][] makeSet(List data){
Iterator<?> itr1 = data.listIterator();
double[] ix = new double[data.size()];
double[] iy = new double[data.size()];
double[][] x = { makeInnerSet(data, iy,0), makeInnerSet(data, ix,1) };
return x;
}
EDIT
Well making making the code :
double[][] x = {
makeInnerSet(data, new double[data.size()],0),
makeInnerSet(data, new double[data.size()],1)
};
Half-found my answer...seconds later...
I certainly now don't need the ix, iy. But how do I take the number of columns in the List ?
Assuming all arrays in the list have the same size (because otherwise makeinnerset would bomb ,too):
int columns = ((Object[])data.first()).size()
the code gets the first array and get its size which should be the same for all arrays.

How to generate numbers from an array randomly,with each number being unique

I hav a numeric array,which contains 20 elements.I am displaying the numbers randomly for a blackberry application,bt i want dat all d numbers generated should b unique.It should b randomly generated,bt it has b unique until all the elemnts in the array is exhausted.I am giving the piece of code here,if anyone can help me out,i will b extremely grateful.
static int quesNum[] = new int[20];
static int quesCount = -1;
private static void initialize(){
Random rgen = new Random(); // Random number generator
//--- Initialize the array
for (int i=0; i<quesNum.length; i++) {
quesNum[i] = i;
}
//--- Shuffle by exchanging each element randomly
for (int i=0; i< quesNum.length; i++) {
int randomPosition = rgen.nextInt(quesNum.length);
int temp = quesNum[i];
quesNum[i] = quesNum[randomPosition];
quesNum[randomPosition] = temp;
}
}
/*Changed the code to get a unique random number
*/
public static int getQuestionNumber() {
quesCount++;
if(quesCount < quesNum.length){
return quesNum[quesCount];
}
else{
initialize();
quesCount = -1;
return getQuestionNumber();
}
}
Shuffle first, then iterate:
Collections.shuffle(listOfValues);
for(Integer val : listOfValues) {
// give it to user
}
UPDATE
Some wording of OP makes me think Collections.shuffle() is not supported on Blackberry. Then advise is to copy the code of Collections.shuffle(List,Random) into the application.
What you're describing is a perfect application for just shuffling the array.
int len = 20;
Integer[] arr = new Integer[len];
for(int i =0;i<len;i++){
    arr[i] = Integer.valueOf(i+1);
}
Collections.shuffle(Arrays.asList(arr));
Now the array is shuffled and you can iterate over it.
You can use an ArrayList instead of the Array and delete each generated number.

Categories