Creating an Array that contains multiple arrays - java

I have created two classes, one called "Bucket", and the other called "Player".
In "Bucket", I have a constructor method that creates a virtual bucket (i.e. small array) that contains three values - 1, 1, and 1. As well, I created a method to get the bucket array.
In the "Player" class, I have created a method that uses a larger array (I have called this larger array "ArrayOfBuckets"), which uses a loop to store a new bucket at each index value, up until a certain point (when i>NumberSticks). However, when I try to set
ArrayofBuckets[i] = bucketInstance.getBucket();
I get an error from Eclipse, saying that "Type mismatch: cannot convert from Bucket to int". I have spent an hour trying to solve this, to no avail. Any help would be really nice. Thanks a lot, and here is all the code that is used:
The Player Class:
import java.util.Scanner;
public class Player {
Scanner scan = new Scanner(System.in);
public String name;
private int pType;
private int[] ArrayOfBuckets;
public Player(String tempName)
{
this.name = tempName; //this. is unneccessary
}
public void ArrayOfBuckets(int NumberSticks) //this is a constructor method and creates the arrays that contains a
{
ArrayOfBuckets = new int[NumberSticks];
int i = 0;
while(i<NumberSticks)
{
Bucket bucketInstance = new Bucket();
ArrayOfBuckets[i] = bucketInstance.getBucket();//new Bucket(); //ADD THIS
i++;
}
}
and the Bucket Class:
import java.util.Random;
public class Bucket {
// private int[][] largeArray = null; //WTF DO I DO HERE
private int AIChoiceStick;
private int[] bucket;
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 Bucket()
{
bucket = new int[3];
bucket[0] = 1;
bucket[1] = 1;
bucket[2] = 1;
public int[] getBucket()
{
return bucket;
}

You're speaking about a two-dimensional array.
private int[][] ArrayOfBuckets;
Your ArrayOfBuckets (should be just buckets according to naming conventions) is an array of arrays, so it gets two sets of square brackets.
Then the initialization:
ArrayOfBuckets = new int[NumberSticks][3];
By the way, if you want to have room for 50 elements in an array, then initialize it new int[50] so it will have indexes 0 through 49.

Related

Adding more variables to an array of objects in java

I've made a bit of a mess on a project of mine. I have to create an array of objects. I have made an array but it only has 1 field 'myMonths' referring to the length of time of the project.
In my main method:
case 1:
int n = 1; //int n = number of projects
Scanner sc = new Scanner(System.in);
//myMonths = new int[amount];
System.out.println("** Only projects with a duration between 2 and 12 months can be included **");
System.out.println("What was the duration of your projects in months?");
for(int i=0; i<1; i++){
int a = sc.nextInt();
//display error message
if((a < 2) || (a > 12)){
System.out.println(" Please enter an amount between 2 and 12 months. ");
}
//add to the array
else{
myMonths[index++] = a;
}
}
calc.setMyMonths(myMonths); //creating the object
break;
In my class on separate file:
public class MenuTestClass{
private int myMonths[];
private double average; //store average value of numbers
private boolean averageCanBeCalculated;
private int max; // store max number from array. to be calculated
public MenuTestClass(){
myMonths = new int[5];
}
public MenuTestClass(int[] myMonths){
this.myMonths = myMonths;
}
public void setMyMonths(int[] values){ //declare setter method
myMonths = values;
}
I should have added in two more fields, both strings. Is there a way I can add more fields/attributes to this array and have them viewable at the same time under 1 index? For example at [0] projectName, projectManager, myMonths ie(string, string, integer).
Any advice would be great, I am getting really confused with OOP. Thanks in advance!
Yes, create a class containing your three properties:
class MyContainer {
public MyContainer(int durationMonths, String projectName, String projectManager) {
this.durationMonths = durationMonths;
this.projectName = projectName;
this.projetManager = projectManager;
}
public int durationMonths;
public String projectName;
public String projectManager;
}
Then create an array of this class with:
MyContainer[] myArray = new MyContainer[numberOfProjects];
Add items to the array like this:
myArray[0] = new MyContainer(3, "super project", "awesome manager");

How do you make an Arraylist of RandomNumber integers? java

So I am relatively new to the programming scene and I am confused as to why my code doesn't work. I am trying to make an arraylist of flowers and then use a random number generator to create a random number of certain flowers, and store them in the array. In my logic, I thought that I created a variable to store the numbers (ex randomRoses) and stored the number in the array so I could easily print out how many of each flower there is by just calling the arraylist and the position. (ex flowerArray[0] would print out 8 Roses) but sadly it does not.
public class Flower
{
private int randomRoses;
private int randomTulips;
private int randomOrchids;
public ArrayList <Integer> flowerArray;
public Flower()
{
r = new Random();
t = new Random();
o = new Random();
int randomRoses = (r.nextInt(10) + 0);
int randomTulips = (t.nextInt(10) + 0);
int randomOrchids = (o.nextInt(10) + 0);
flowerArray = new ArrayList<Integer>
}
public void add2Array ()
{
flowerArray.add(randomRoses); //flowerArray[0] is the # of roses
flowerArray.add(randomTulips); //flowerArray[1] is the # of tulips
flowerArray.add(randomOrchids); //flowerArray[2] is the # of orchids
}
public void printArray()
{
System.out.println(flowerArray[0]);
}
You can use the same random object, no need to create 3 instances of it for the random integer generation,
Random r = new Random();
for (int i = 0; i < 3; i++) {
flowerArray.add(r.nextInt(10));
}
System.out.println(flowerArray);
you can not do flowerArray[0] because you have an arrayList and not an array.
you can instead do: flowerArray.get(0) for getting the integer at pos zero
Here your array list is associated with a class object. When you initialize your array list you need to add your entries to the array list in the constructor itself. So when you say object.printArray() its actually returning you the empty array list, that's why you are getting 0 every time. Try This.
class Flower
{
private int randomRoses;
private int randomTulips;
private int randomOrchids;
public ArrayList<Integer> flowerArray;
public Flower()
{
Random r = new Random();
Random t = new Random();
Random o = new Random();
int randomRoses = (r.nextInt(10));
int randomTulips = (t.nextInt(10));
int randomOrchids = (o.nextInt(10));
System.out.println(randomRoses);
System.out.println(randomTulips);
System.out.println(randomOrchids);
flowerArray = new ArrayList<Integer>();
flowerArray.add(randomRoses); //flowerArray[0] is the # of roses
flowerArray.add(randomTulips); //flowerArray[1] is the # of tulips
flowerArray.add(randomOrchids); //flowerArray[2] is the # of orchids
}
public void printArray()
{
System.out.println(flowerArray.get(0));
}
}
public class Test {
public static void main(String[] args) {
Flower f = new Flower();
f.printArray();
}
}
And in array list you can get elements by using get(index) method.
This will give the output you expect.
public void printArray
{
System.out.println(flowerArray.get(0)+" Roses");
System.out.println(flowerArray.get(1)+" Tulips");
System.out.println(flowerArray.get(2)+" Orchids");
}
Also you missed a semi-colon after the statement defining the arraylist.
Make the correction:
flowerArray=new ArrayList<Integer>;
How did it compile without that semi-colon?
It is not working because your syntax for getting the ith flower is wrong.
You're using a java.util.ArrayList so the correct way to get an object from that ArrayList is by calling the get() method.
System.out.println(flowerArray.get(0));
Hope that helps.

How do I create a method to grab a random value from another class?

I am trying to randomly grab integers from another class and cannot figure out how to get those values. The first class is my initial random number generator. The second class is the class I am trying to retrieve these numbers to. I have created a grab method but cannot figure out how to retrieve these random integers from class ArrayBag. Any help would be appreciated!
import java.util.Random;
public final class ArrayBag<T> implements BagInterface<T>
{
private final T[] bag;
private int numberOfEntries;
private boolean initialized = false;
private static final int DEFAULT_CAPACITY = 6;
private static final int MAX_CAPACITY = 10000;
/** Creates an empty bag whose initial capacity is 6. */
public ArrayBag()
{
this(DEFAULT_CAPACITY);
System.out.print("Generating 6 random integers 1 - 6 in ArrayBag\n");
//Random loop to generate random numbers 1 to 6
Random rand = new Random();
for(int start=1; start <=6; start++)
{
int randInt = rand.nextInt(6);
System.out.println("Generated : " + randInt);
}
System.out.println("Finished\n");
} // end default constructor
This is my second class and method...
import java.util.Random;
public class PopulationBag
{
public PopulationBag()
{
ArrayBag ab = new ArrayBag();
LinkedBag lb = new LinkedBag();
}
/**
* Grab Method
*/
public int grab()
{
ArrayBag ab = new ArrayBag();
Random grab = new Random();
for(int start = 1; start <= 6; start++)
{
int randGrab = grab.nextInt(ab);
System.out.println("Randomly grabbed values : " + randGrab);
}
}
}
As far as I understant what you are trying to do is to build a class which genereates and holds a user-given number of random ints and second class which can access the values generated by the first class.
I've noticed a few issues with your approach. Firstly, you are generating the random numbers but never store them anyway. If the number of random ints is given by a user, you can try ArrayList approach, or use a new Java 8 approach with the method ints() of Random class (which I used in the code below). You would also need a getter method to make the access to your private variable possible.
Consider the code:
public class ArrayBag {
private int[] randomBag;
private boolean initialized = false;
private static final int DEFAULT_CAPACITY = 6;
private static final int MAX_CAPACITY = 10000;
public ArrayBag() {
Random random = new Random();
randomBag = new int[DEFAULT_CAPACITY];
// The method ints introduced in Java 8 accepts three params:
// number of ints generated, upper and lower bound between which the ints will be generated.
// toArray method passes the generated nums as an dynamically created array,
// which you can assign to a variable.
randomBag = random.ints(DEFAULT_CAPACITY, 1, DEFAULT_CAPACITY + 1).toArray();
}
// the 'getter' method
public int getRandomInt(int i) {
return randomBag[i];
}
}
/* Second class */
public class PopulationBag {
private ArrayBag ab = new ArrayBag();
private Random grab = new Random();
// Are the numbers form the ArrayBag going to be grabbed at random,
//or simply one after another?
public int[] grabInOrder(int numberOfGrabbedInts) {
// Create an array to hold ints.
int[] intBag = new int[numberOfGrabbedInts];
// Fill in data to the intBag
for (int i = 0; i < numberOfGrabbedInts; i++) {
// Call getRandomInt() method form ArrayBag class
intBag[i] = ab.getRandomInt(i);
System.out.println("Randomly grabbed values : " + intBag[i]);
}
return intBag;
}
private int[] grabAtRandom(int numberOfGrabbedInts) {
int[] intBag = new int[numberOfGrabbedInts];
for (int i = 0; i < numberOfGrabbedInts; i++) {
// This is kind of funky, basically it returns at random the ints saved in ArrayBag.
intBag[i] = ab.getRandomInt(grab.ints(1, 1, numberOfGrabbedInts).findFirst().getAsInt());
System.out.println("Randomly-randomly grabbed values : " + intBag[i]);
}
return intBag;
}

Cloning an object and its inside arrays in Java DIY

I am trying to clone an object without using any library.
The object has other objects/arrays/matrixes in it.
So I developed some methods to clone those as well.
They are working fine when I am cloning arrays/matrixes that are not inside the object.
These are the methods:
public static int[] cloneArray(int[] array){
int i = 0;
int[] clone = new int[array.length];
while (i < array.length){
clone[i] = array[i];
i++;
}
return clone;
}
public static int[][] cloneMatrix(int[][] matrix){
int[][] clone = new int[matrix.length][matrix[0].length];
for (int i = 0;i<matrix.length;i++)
for(int j = 0;j<matrix[0].length;j++)
clone[i][j] = matrix[i][j];
return clone;
}
However, when I want to clone an object, the references of the array/matrix stay the same, as you can check in the output on the bottom of the post.
This is the constructor I have:
public State(int parentStateID, int stateID, int[][] board, int[] pieces, int points, int acquiredPoints){
State.parentStateID = parentStateID;
State.stateID = stateID;
State.currentBoard = cloneMatrix(board); //here takes place the matrix cloning
State.currentPieces = cloneArray(pieces); //here takes place the array cloning
State.totalPoints = points;
State.acquiredPoints = acquiredPoints;
}
And this is the cloning method:
public static State cloneState(State state){
int[][] currentBoard = state.getCurrentBoard();
int[] currentPieces = state.getCurrentPieces();
int totalPoints = state.getTotalPoints();
int acquiredPoints = state.getAcquiredPoints();
int parentStateID = state.getParentStateID();
int stateID = state.getStateID();
State clone = new State(parentStateID,
stateID,
currentBoard,
currentPieces,
totalPoints,
acquiredPoints);
return clone;
}
To better visualize the output, here are the arrays and matrix:
public static int piecesList[] = {1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};
public static int piecesList2[] = {2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};
public static int piecesList3[] = {3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};
private static int[][] map = {{0,1,2,3,4},{5,6,7,8,9},{10,11,12,13,14},{15,16,17,18,19},{20,21,22,23,24}};
Here is the verification code:
int[][] state2 = cloneMatrix(map);
state2[0][0] = 1;
System.out.println("map.original " + map[0][0]);
System.out.println("map.clone " + state2[0][0]);
System.out.println("");
System.out.println("");
int[] pc = cloneArray(piecesList);
pc[24] = 1;
System.out.println("pieces.original " + piecesList[24]);
System.out.println("pieces.clone " + pc[24]);
System.out.println("");
System.out.println("");
State newState = setFirstState();
State clonedState = cloneState(newState);
clonedState.setCurrentPieces(piecesList2);
System.out.println("newState.pieceslist: "+newState.getCurrentPieces()[0]);
System.out.println("clonedState.pieceslist: "+clonedState.getCurrentPieces()[0]);
System.out.println("piecesList.original: "+piecesList[0]);
System.out.println("");
newState.setCurrentPieces(piecesList3);
System.out.println("newState.pieceslist: "+newState.getCurrentPieces()[0]);
System.out.println("clonedState.pieceslist: "+clonedState.getCurrentPieces()[0]);
System.out.println("piecesList.original: "+piecesList[0]);
And here is the output:
map.original 0
map.clone 1
pieces.original -1
pieces.clone 1
//as you can check in the next two cases, the change takes effect in both the original state, and the cloned state
newState.pieceslist: 2
clonedState.pieceslist: 2
piecesList.array variable: 1
newState.pieceslist: 3
clonedState.pieceslist: 3
piecesList.array variable: 1
Been trying to solve this issue for over 12 hours, without much success...
I have tried libraries as well as serialization with no success...
Help is much appreciated!
The problem with your code is that the fields (not shown) obviously are static, as can be told from your constructor:
public State(int parentStateID, int stateID, int[][] board, int[] pieces, int points, int acquiredPoints){
State.parentStateID = parentStateID;
State.stateID = stateID;
State.currentBoard = cloneMatrix(board); //here takes place the matrix cloning
State.currentPieces = cloneArray(pieces); //here takes place the array cloning
State.totalPoints = points;
State.acquiredPoints = acquiredPoints;
}
The constructor should instead read like this:
public State(int parentStateID, int stateID, int[][] board, int[] pieces, int points, int acquiredPoints){
this.parentStateID = parentStateID;
this.stateID = stateID;
this.currentBoard = cloneMatrix(board); //here takes place the matrix cloning
this.currentPieces = cloneArray(pieces); //here takes place the array cloning
this.totalPoints = points;
this.acquiredPoints = acquiredPoints;
}
A field which is static exists only once per class. A field which is not static exists once per each object constructed from that class (or any subclass). Because of that, you actually created objects which are empty, and whatever you thought you would store in the object you actually stored in the class, thus sharing the same data among all objects.
As a rule of thumb, you usually do not want any static non-final fields in your classes. Exceptions apply, but they're rare and mostly limited to a few tiny bootstrapping things in frameworks.

Java: Initializing a new LinkedList Collection

I am trying to build a simple card game as a personal exercise. I have a collection Cards that should contain my deck. To initialize it, I want to pass it a map of what the deck should look like - an integer array (1 to n, 1 to 2) with (n, 1) containing a card type which is resolved within the card class, and (n, 2) containing the number of cards that type I want in the deck. I'm having difficulties with a NullPointer exception, however. Here is my Cards class:
import java.util.LinkedList;
public class Cards{
private LinkedList<Card> CardDeck;
...
public boolean MakeDeck(int[][] DeckMap){
/*feed the function a 2D int array (0 to n, 0 to 1)
#Param - DeckMap[][] - [n][0] to contain card type
[n][1] to contain DupeCount*/
//search the array for duplicates
for (int i = 0; i < DeckMap.length; i++){
int hold = DeckMap[i][0];
DeckMap[i][0] = -10;
for (int j = 0; j< DeckMap.length; j++){
if (DeckMap[j][0] == hold){
DeckMap[i][0] = hold;
return false;
}
}
DeckMap[i][0] = hold;
}
//Add the cards
// tried variations on this: CardDeck = new LinkedList<Card>;
for (int i = 0; i< DeckMap.length; i++){
Card cC = new Card();
cC.initializeCard(DeckMap[i][0], DeckMap[i][1]);
CardDeck.addLast(cC);
}
return true;
}
}
The NullPointer error occurs at the cC.addLast line - since I have initialized the Card class, the Null Pointer should refer to the CardDeck LinkedList I want to add the Card to, I think. But I can't work out how to initialize the list. Or is the .initializeCard call the problem (code below)? Thanks in advance for your help and apologies if I've missed something obvious.
Error:
java.lang.NullPointerException
at towergame.Cards.MakeDeck(Cards.java:75)
public class Card {
private static String cName;
private static int cDuplicateCount;
public static cEffect myEffects;
public final void initializeCard(int inEffect, int DupeCount){
myEffects = new cEffect();
myEffects.setEffect(inEffect);
cName = myEffects.getCardType();
cDuplicateCount = DupeCount;
}
...
}
Instead of this private LinkedList<Card> CardDeck;
use this private LinkedList<Card> CardDeck = new LinkedList<Card>();
it is throwing NPE because cardDeckhas not been initialized.

Categories