How to set up constructor and methods with ArrayList? - java

I'm trying to learn about how constructors and methods work. I pretty much have the concepts down, it's just that I don't know how to set them up. I especially don't know how to use them with ArrayLists.
I'm trying to calculate and print the area of a rectangle, the commented parts are what I don't know how to set up.
import java.util.ArrayList;
class RectangleStats
{
// Private instance variables
// length is an ArrayList which will contain integer values, width is an array which will contain integer
// values, and area is an array which will contain decimal values.
//code goes here for instance variables goes here
// The constructor for the RectangleStats class takes an ArrayList and an array as parameters for
// length and width, respectively.
// code for constructor goes here
// The calcRectangleArea() method calculates the area of rectangles using the length and
// the width assigned to the private instance variables and assigns the results to the area array of type
// double. This method does not return anything.
// code for the calcRectangleArea() method goes here
// The printArea() method prints the values assigned to the area array using the most appropriate
// type of loop. This method does not return anything.
// code for the printArea() method goes here
}
// The RectangleStatsTesterClass assigns the length of two rectangles to an ArrayList and assigns the
// width of two rectangles to an array. The calcRectangleArea() and printArea() methods are invoked to
// calculate and print the area of the two rectangles.
public class RectangleStatsTesterClass2
{
public static void main(String[] args)
{
ArrayList intLength = new ArrayList();
intLength.add(7);
intLength.add(5);
int [ ] intWidth = {3, 4};
RectangleStats rectStats = new RectangleStats(intLength, intWidth);
rectStats.calcRectanglePerimeter();
rectStats.printArea();
}
}

Try like this:
import java.util.ArrayList;
import java.util.List;
class RectangleStats
{
private List<Integer> length;
private int[ ] width;
double areas[];
RectangleStats(List<Integer> length, int[] width){
this.length = length;
this.width = width;
this.areas = new double[this.width.length];
}
private void calcRectangleArea(){
for(int i=0; i<width.length; i++){
areas[i] = length.get(i) * width[i];
}
}
public void printArea(){
calcRectangleArea();
for(int i=0; i<areas.length; i++){
System.out.println("Area " + i + " : " + areas[i]);
}
}
public void calcRectanglePerimeter(){
for(int i=0; i<width.length; i++){
System.out.println("Parameter for "+ i +"th Rectangle : " + (2 * (length.get(i) + width[i])));
}
}
}
public class RectangleStatsTesterClass2
{
public static void main(String[] args)
{
ArrayList<Integer> intLength = new ArrayList<Integer>();
intLength.add(7);
intLength.add(5);
int [ ] intWidth = {3, 4};
RectangleStats rectStats = new RectangleStats(intLength, intWidth);
rectStats.calcRectanglePerimeter();
rectStats.printArea();
}
}

Related

How do I remove random object inside array? New to java

I'm doing a small project where I have two different types of ball objects inside a bag array and I want to take two random objects from that bag. The problem that I am having is removing the objects from that bag array. I am succeeding to take two random objects but it takes in their position in the bag array and I don't really know how to remove objects from that bag array.
public class Bag {
public static void main(String[] args) {
Balls whiteBalls = new Balls("White");
Balls blackBalls = new Balls("Black");
Balls[] objArray;
whiteBalls.setAmount(16);
blackBalls.setAmount(20);
int totalBalls = whiteBalls.getAmount() + blackBalls.getAmount();
// Create two arrays that hold white and black balls together.
Balls[] white = new Balls[whiteBalls.getAmount()];
Balls[] black = new Balls[blackBalls.getAmount()];
// Adding white balls into array "white".
for (int i = 0; i < whiteBalls.getAmount(); i++) {
white[i] = new Balls("White");
} // Adding black balls into array "black"
for (int i = 0; i < blackBalls.getAmount(); i++) {
black[i] = new Balls("Black");
}
Balls[] bag = new Balls[totalBalls]; // Making a bag which holds all the balls.
// Copy's both arrays and fills up array "bag".
System.arraycopy(white, 0, bag, 0, whiteBalls.getAmount());
System.arraycopy(black, 0, bag, 16, blackBalls.getAmount());
//System.out.println(Arrays.toString(bag));
int count = 0;
Random rnd = new Random();
String[] colours = new String[]{"White", "Black"};
while(bag.length != 1){ // Depending on what colour the balls are either black ball or white ball is placed back into the bag.
count++;
int select1 = rnd.nextInt(colours.length);
int select2 = rnd.nextInt(colours.length);
while(white.length != 0 || black.length != 0){
if(select1 == 0 && select2 == 0){
System.out.println("Both are the same colour. " + select1 + " " + select2);
}
}
}
}
}
The other problem that I am running into is in my other class which balls one method 'getColour()' doesn't want to work for some reason.
public class Balls {
private String colour;
private int amount;
public Balls(String type) {
colour = type;
}
public String getColour() {
return colour;
}
public void changeAmount(int num){
this.setAmount(num);
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public String toString() {
return colour;
}
}
Any feedback is appreciated. Thank you for reading and thanks in advance.
I'd recommend you using an ArrayList, as it provides methods to remove elements from within the list (be aware, as this can be quite costly in a large array). The remove() method can take an index of the object to remove or the object to remove itself, as the method is overloaded. Be aware, as storing to int's that hold the index of the element in the bag that should be removed, can result in unexpected results, as it can be, that this index points to the wrong object after you removed an object after you stored the indices.So, I hope this answer helps you.

How to find Values stored in object in an Array list in Java

I have read a lot of posts about this and nothing I've tried seems to work. Any help would be greatly appreciated.
I have 2 Classes, ColouredShape and ShapeMatchingGame.
I'm trying to create ColouredShape objects using 2 arguments and add them to an ArrayList in the ShapeMatchingGame Class.
I need 4 shapes and 3 colours of each of the 4 shapes * 3, so 36 items in the array.
I can see 36 objects are adding to the array in the loop but whenever i try to access the values of the objects in the array im not seeing the expected values for the object at its index.
I guess what I'm trying to ask is am I accessing the values incorrectly or have I done something wrong with creating the objects and adding them to the array?
public class ColouredShape {
static int shapeValue;
static int colourValue;
static String colour, shape;
public ColouredShape() // Default constructor
{
this.shapeValue = 1;
this.colourValue =1;
this.colour ="";
this.shape ="";
}
public ColouredShape (int shapeValue,int colourValue) // Constructor with 2 arguments
{
this.shapeValue = shapeValue;
this.colourValue =colourValue;
this.colour = colour;
this.shape =shape;
}
public int getColour()
{
return colourValue;
}
public int getShape()
{
return shapeValue;
}
public class ShapeMatchingGame {
static int noShapes;
static ArrayList<ColouredShape> ColouredShapes = new ArrayList<ColouredShape>();
static int index;
static int shapeValue=1;
static int colourValue;
public static void main(String[] args)
{
ObjectCreation();
}
public static void ObjectCreation()
{
do// runs loops 3 times to create 3 of every shape/colour combo
{
do // loop to continue onto the next shape until 4 are created
{
do // loop to create 3 of colours of same shape
{
colourValue++;
System.out.println("Shape value " +shapeValue + " colour value " +colourValue);
ColouredShape gameShapes = new ColouredShape(shapeValue,colourValue);
ColouredShapes.add(gameShapes);//creates an object of colourshapes and passes the current shapevalue + colourvalue as arguments then adds it to the arraylist
System.out.println ("Value of object at array index "+ index + " shape value " + ColouredShapes.get(index).getShape()+" colour value " +ColouredShapes.get(index).getColour()+ "colour variable value = " + colourValue);
index++;
for (ColouredShape colouredShape : ColouredShapes)
{
System.out.println(colouredShape.getClass().getName() + "/" +
colouredShape.shape + "/" +
colouredShape.colour);
}
}while(colourValue < 3 );
System.out.println ("Value of object at array index "+ "0" + " shape value " + ColouredShapes.get(0).getShape()+" colour value " +ColouredShapes.get(0).getColour()+ "colour variable value = " + colourValue);
colourValue=0;//reset colourValue to allow next iteration of the loop
shapeValue++;//incrementing shapeValue to add colours to next shape
System.out.println ("Value of object at array index "+ "0" + " shape value " + ColouredShapes.get(0).getShape()+" colour value " +ColouredShapes.get(0).getColour()+ "colour variable value = " + colourValue);
}while(shapeValue < 5 );
shapeValue=1; // resetting shapeValue to allow next iteration of the loop
noShapes++;
}while (noShapes<3);
}
}
There are several problems on your ColouredShape:
shapeValue and colourValue are static. This means there they are 'global' variables. Doesn't matter how many Colouredshapes you create, all of them will have the same values
the constructor sets the value of the static variables only, and you print the values of the string text.
Change the Object to be like this:
public class ColouredShape {
int shapeValue;
int colourValue;
public ColouredShape() // Default constructor
{
this.shapeValue = 1;
this.colourValue = 1;
}
public ColouredShape(int shapeValue, int colourValue) // Constructor with 2
// arguments
{
this.shapeValue = shapeValue;
this.colourValue = colourValue;
}
public int getColour() {
return colourValue;
}
public int getShape() {
return shapeValue;
}
}
and the result should be as expected

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;
}

How Can I display the contents of void method?

I am new to programming and Java as well. I need to write a void method which sorts the array entered, I have the code written but do not know how to display the sorted list from void method. Anyone willing to help. It will be greatly appreciated.
package util.assign4;
import java.util.StringTokenizer;
import javax.swing.JOptionPane;
import util.IO;
public class UtilAssign4 {
public static int[] getData (String input){
StringTokenizer st = new StringTokenizer(input);
int []x = new int[st.countTokens()];
for(int i = 0;st.hasMoreTokens(); i++){
try{
x[i] = Integer.parseInt(st.nextToken());
}
catch(Exception e){
JOptionPane.showMessageDialog(null," Invalid input");
System.exit(1);
}
}
return x;
}
public static int getHighest(int g[]){
int hi = g[0];
for( int k = 1; k <g.length;k++)
if(g[k]> hi) hi = g[k];
return hi;
}
public static int getSmallest(int p[]){
int sm = p[0];
for(int l = 1;l<p.length;l++)
if(p[l] < sm) sm = p[l];
return sm;
}
public static float getAverage(int n[]){
float sum = 0.0f;
for(int y = 0;y <n.length; y++) sum += n[y];
return sum/n.length;
}
public static void getSorted(int grades []){
for(int i = 0; i<grades.length-1;i++){
int largest =i;
for(int j = 0;j<grades.length;j++)
if(grades[j]>grades[largest]) largest = j;
int temp = grades[largest];
grades[largest] = grades[i];
grades[i]=temp;
}
}
public static void main(String[] args) {
String input = JOptionPane.showInputDialog("Enetr one or more grades:");
int [] x = getData(input);
int j = getHighest(x);
int m = getSmallest(x);
float a = getAverage(x);
IO.showMsg("Array you entered:" + input + String.format("\nThe"
+ " higheset grade is:%2d \n"
+ "The Lowest Grade is:%2d \n"+"The average is:%2.2f\n"
+ "The sorted list: ",
j,m,a));
}
}
You are not supposed to print the contents of the array in the sort method. Your requirement (I wager) is to sort the array supplied to the method 'in-place' (which it already looks like you are doing). What this means is that given an array:
int[] grades = new int[] {34, 76, 12, 0, -1};
That when you call:
UtilAssign4.getSorted(grades);
That the array passed into the method is actually sorted inside the method, and as such does not need to be returned (that's why your return type is void). So to summarize, before calling the sort method, your array is unsorted. After the call completes, tbe very same array has now been sorted.
So now you can then print out the sorted array in the calling method (in this case main(String[]):
getSorted(x); // <-- call the sort function, on your array
String msg = String.format("\nThe higheset grade is:%2d \n"
+ "The Lowest Grade is:%2d \nThe average is:%2.2f\n"
+ "The sorted list: %s", j, m, a, Arrays.toString(x));
IO.showMsg(msg);
Note the Arrays.toString(x)? That will take your sorted array, and convert it into a string representation (will look something like this: [76, 34, 12, 0, -1]).
in void method short your array in any field Array that is
public class UtilAssign4 {
private Integer[] shorted = new Integer[100];
public static int[] getData (String input){
.
.
}
and do your stuff with above array in your void method and use this where you want

Constructor undefined

I have a problem with my code, in that it keeps saying that the constructor is undefined. I already read somewhere that I need to declare the constructor with no arguments. I just don't know how to do that.
If someone could help, I am new at java and programming. My code is below:
import java.util.*;//import library
class Input
{
public Input (int size,int startV,int endingV)
{
//declarations of variables
double difference;
double[] array= new double[size];
array[0]=startV;
//calculating the difference to add on each number in the array
difference=(endingV-startV)/size;
for (int counter=1;counter<size;counter++) //for loop to fill the array
{
array[counter]=array[counter-1] + difference;
}
}
public Input enter(int size,int startV,int endingV)
{
//declarations of variables
double difference;
double[] array= new double[size];
array[0]=startV;
//calculating the difference to add on each number in the array
difference=(endingV-startV)/size;
for (int counter=1;counter<size;counter++) //for loop to fill the array
{
array[counter]=array[counter-1] + difference;
}
return this;
}
}
class Show
{
public Show (int size,double[] array)
{
for (int i=0;i<size;i++) //for loop to print the array
System.out.println("This is the array " + i+ ": " + array[i]);
}
public Show print(int size,double[] array)
{
for (int i=0;i<size;i++) //for loop to print the array
System.out.println("This is the array " + i+ ": " + array[i]);
return this;
}
}
public class Assignment2
{
public static void main(String[] args)
{
//declaring variables
int startV,endingV;
int size=0;
System.out.print("Give the size of the array:");//Print message on screen
size = new Scanner(System.in).nextInt();//asking for the size of array
double[] array= new double[size]; //creation of array
System.out.print("Give the starting value of the array:");
startV = new Scanner(System.in).nextInt();//asking for the starting value of array
System.out.print("Give the ending value of the array:");
endingV = new Scanner(System.in).nextInt();//asking for the last value of array
//calling the functions from the other classes
Input enter= new Input(size,startV,endingV);
Show print= new Show(size,array);
}
}
You're close:
You have a method:
public Method enter(int size,int startV,int endingV) {
to make it a constructor it's signature must be
public Method (int size,int startV,int endingV) {
and you then have to delete the return this; statement.
Remember, constructors don't have a return type and their name is identical to the name of the class. With this information, you'll also be able to fix the Method1 constructor.
Also, please respect the Java naming conventions and have variables start with a lower-case letter to improve the readability of your code.
You need to create a
public Method(size,startV,endingV)
not
public Method enter = (size, startV, endingV)
The first is a constructor the second is a method
For class Method
the default constructor will be
public Method(){}
For class Method1
the default constructor will be
public Method1(){}
in your classes there are no constructors as the
constructor name must be will the same as class name.
enter(int size,int startV,int endingV)
and
print(int size,double[] array)
can be two methods in your classes.
also your two constructor can be -
public Method(int size,int startV,int endingV){ /..../}
and
public Method1(int size,double[] array){ /..../}
Your constructor must have the same name than your class and has no return type. So for your class Method, your constructor will simply be :
public Method(int size, int startV, int endingV)
{
// code...
}
Please also note that constructors exist to initialize your instances of objects, if you want to create a method that does a specific calcul, then yes, you'll have to do :
public int enter(int size, int startV, int endingV)
{
int result = 0;
// code to calculate, for example result = size + startV + endingV ...
return result;
}

Categories