I am trying to define a method called add() that adds an object Fish to an array fish[]. How would I got about this without using arrayList? I keep receiving the error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
public class Pond {
private Fish[] fish;
private int numFish ;
private int capacity;
public Pond(int capacity){
this.capacity = capacity;
}
public int getNumFish(){ return numFish;
}
public boolean isFull(){//Ponds can only have so many fish
boolean Full = false;
if (numFish >= capacity){
Full = true;}
return Full;
}
public void add(Fish aFish) {// puts a fish in the pond--OR-- replaces a fish that has been temporarily removed
if (numFish < capacity){
fish[numFish++] = aFish;}
}
Here dynamic array solution, which is a simple implementation of ArrayList method.
public void add(Fish aFish) {
ensureCapacity();
fish[numFish++] = aFish;
}
private void ensureCapacity() {
if (numFish == fish.length) {
int newSize = fish.length * 2;
Fish[] newFish = new Fish[newSize];
System.arraycopy(fish, 0, newFish, 0, fish.length);
fish = newFish;
}
}
In your constructor for pond you can add fish = new Fish[capacity] to set the initial size of the fish array to the capacity of your pond. Remember you can not add values to an array only change the values already there.
Related
I have created a stack .
public class STK {
static int capacity = 0;
STK(int size) {
capacity = size;
}
int stackk[] = new int[capacity];
int top = 0;
public void push(int d) {
if(top < capacity) {
stackk[top] = d;
top++;
} else {
System.out.println("Overflow");
}
}
}
its implementation
public class BasicStackImplementation {
public static void main(String[] args) {
STK mystack = new STK(5);
mystack.push(51);
mystack.push(23);
}
}
when i try to run this code it gives an error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at STK.push(STK.java:21)
at BasicStackImplementation.main(BasicStackImplementation.java:6)
Field initializers run before the constructor. Your code is equivalent to this:
static int capacity = 0;
int stackk[]=new int[capacity];
STK(int size)
{
capacity=size;
}
So you're initializing an empty array. To fix it, just initialize stackk inside the constructor:
int[] stackk;
STK(int size)
{
capacity = size;
stackk = new int[capacity];
}
Also, capacity varies by instance and shouldn't be static.
When you made your class, you initialized your array property in your class to equal capacity which is 0. So your array is initialized with 0 elements.
When you call your constructor and set the capacity value, you need to re-initialize your class array equal to new int[value]
I am trying to to create a stacks which has the following API:
Stacks(int n)// creates stacks of size n
pop() //returns the last element pushed in the stacks
pop(int n) //returns an array of of n elements
push(int e) //appends an element to the stacks
push(int n, ar[]) //appends an array to the stack
The stacks should be able to dynamically change size when needed, so client programs dont have to do it every time.
I have done all that only my problem is when assigning object A to object B doesn't that mean that A will now points to the address of B?
Here is my code and i hope it explaines what i mean
public class Stacks {
/*
* constructs a stack object
* #param n that will determine that size of the stacks to be constructed
*/
public Stacks(int n)
{
this.elemetns= new int[n];
this.size=n;
this.top=-1;
}
/*
* constructs a stack object, with size of 2 when no parameter is given
*/
public Stacks()
{
this.elemetns= new int[2];
this.size=2;
this.top=-1;
}
public int pop()
{
if (top<0)
{
System.out.println("Error code 2: Empty stacks");
return -1;
}
else
{
int n= this.elemetns[top];
top--;
return n;
}
}
public int [] pop(int size)
{
if (this.size<size)
{
System.out.println("Error code 3: The Maximum number of elements that can be acquired is "+ this.size);
return null;
}
else
{
int res[]= new int[size];
for (int i=0;i<size;i++)
{
res[i]=pop();
}
return res;
}
}
public void push(int e)
{
if (!isFull())
{
this.elemetns[++top]=e;
System.out.println(e+" has been pushed to the stack ");
}
else
{
updateStacksSize(this);
this.elemetns[++top]=e;
System.out.println(e+" has been pushed to the stack ");
}
}
public void push(int n,int [] ar)
{
for (int i=0;i<n;i++)
this.push(ar[i]);
}
private void updateStacksSize(Stacks s)
{
int newSize= s.top*2;
Stacks newStacks= new Stacks(newSize);
for (int i = s.top; i>-1;i--)
newStacks.elemetns[i]=s.pop();
s= newStacks;//shouldnt newStacks get garbage collected
//and s gets the new address and attributes of newStacks?
}
private boolean isFull(){return this.size==(this.top+1);}
public static void main(String[] args)
{
Stacks s= new Stacks(5);
for (int i=0;i<7;i++)
s.push(i+1);
System.out.println();
int []arr= s.pop(6);
for (int i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
}
private int elemetns[];
private int top;
private int size;
}
Why does running this program results in problem with the old size although the current object's has been updated.
one more question is it possible to assign this= newStacks instead of instantiating new Stacks object
In Java you assign object references to variables.
I have done all that only my problem is when assigning object A to object B doesn't that mean that A will now points to the address of B?
s= newStacks;//shouldnt newStacks get garbage collected
//and s gets the new address and attributes of newStacks?
It is the other way around since the assignment in Java is from right to left.
"I have done all that only my problem is when assigning object A to object B doesn't that mean that A will now points to the address of B?"
if this is what you meant then:
Stacks A = new Stacks();
Stacks B = A;
Then what this means is that B is now pointing to A.
You're kinda over do it. A stack should consist of a chain of nodes, like an singel-linked list of nodes. I've written an example on this below, see if you can see how it works.
public class Stack <E> {
private StackItem<E> currTop;
private int size;
private int max;
private static class StackItem<E> {
private E e;
private StackItem<E> next;
}
public Stack(int max) {
currTop = null;
size = 0;
this.max = max;
}
public void add(E e){
if ((size+1) == max) throw new StackOverflowError("Max items in stack is reached");
StackItem<E> old = currTop;
currTop = new StackItem<>();
currTop.e = e;
currTop.next = old;
size++;
}
public E getFirst() {
if (currTop == null) return null;
E output = currTop.e;
currTop = currTop.next;
size --;
return output;
}
public E showFirst() {
return currTop.e;
}
public int getSize() {
return size;
}
}
I need help with creating a method that adds input int to an array, and returning a message if array is already full.
I have class Lista with 3 fields numbers, capacity and size. Than I have a counstructor taking int as parameter and seting the capacity of array for the object of Lista class. So far i have this code:
public class Lista {
private int[] numbers;
private int capacity;
private int size;
public Lista (int capacity) {
this.size = 0;
this.capacity = capacity;
this.numbers = new int[capacity];
}
public void addElement(int element) {
}
public static void main(String[] args) {
Lista lista = new Lista(10);
lista.addElement(1);
lista.addElement(2);
lista.addElement(3);
System.out.println(lista.numbers[1]);
I've tried with loops and ArrayLIst but nothing i wrotr realy worked. WHat would be the best way to do it?
You could implement your addElement method like so:
public void addElement(int element) {
if(size == capacity) {
System.out.println("array is full");
return;
}
numbers[size++] = element;
}
You need to throw exception when list is already full and you try to insert next element to it:
class List {
private int[] numbers;
private int nextIndex;
public List(int capacity) {
this.numbers = new int[capacity];
}
public void addElement(int element) {
if (nextIndex < numbers.length) {
numbers[nextIndex] = element;
nextIndex++;
} else {
throw new RuntimeException("list is full");
}
}
public int capacity() {
return numbers.length;
}
public int size() {
return nextIndex;
}
}
I've tried with loops and ArrayLIst but nothing i wrotr realy worked.
WHat would be the best way to do it?
You use an array to store your values, so you don't need to use ArrayList (it is an alternative).
A loop is for iterating. You don't need it either.
I need help with creating a method that adds input int to an array,
and returning a message if array is already full.
Returning a textual message is not really the way which an API should be designed. It should rather returns a boolean to indicate the result of the invocation.
For example, look at the boolean add(E e) method of the Collection interface.
So, you should change the declaration of addElement() in order to return a boolean to indicate if the element was added or not (the last one when the max capcacity was reached).
public boolean addElement(int element) {
if(size == capacity) {
return false;
}
numbers[size++] = element;
return true;
}
If you want to output a textual message, you could test the value of the boolean :
if (!myLista.addElement(5)){
System.out.println("max capacity added. Cannot add the element");
}
Im trying to code an algorithm that can learn by his experiences (in the game connect four). For that I wanted to save all the single steps in a List. But if I am adding Elements to my List, Every Element in the List gets overridden by the Element i am adding. I have no clue why this is like this and even after 1Hour searching I dont know why, because there is no static field in my Runde.java. The code is here: (Im German so dont be suprised by that weird names for the variables)
package me;
public class Runde{
private int[][] spielfeld;
private int[][] x= new int[7][5];
private int lastx;
private int lasty;
public Runde(int[][] spielfeld1, int xi, int jetzgzuege, int y){
spielfeld=spielfeld1;
lastx=xi;
x[xi][4]=jetzgzuege;
lasty=y;
}
public boolean equal(int[][] spielfeld){
if(spielfeld.equals(spielfeld)){
return true;
}else{
return false;
}
}
public void finishround(boolean sieg, int geszuege){
x[lastx][0]+=1;
if(sieg){
x[lastx][1]+=1;
x[lastx][2]+=geszuege;
}else{
x[lastx][3]+=geszuege;
}
}
public int[][] getSpielfeld(){
return spielfeld;
}
public int[][] getData(){
return x;
}
public int getlastx(){
return lastx;
}
public int getlasty(){
return lasty;
}
}
static ArrayList<Runde> liste= new ArrayList<Runde>();
static ArrayList<Runde> Steps= new ArrayList<Runde>();
static void erzeugeGen(){
int[][] spielfeld=leeresSperzeugen();
int x=0;
int y=0;
int zug=0;
int rand = new Random().nextInt(2);
boolean player;
if(rand==1){
player = true;
}else{
player=false;
}
while(!winner(spielfeld,x,y) && zug<42){
zug++;
player=!player;
Runde r;
if(player){
r= Computerzug(spielfeld.clone(),1,zug); // If i have a look in to the spielfeld in this element, its fine
Steps.add(r); // But after adding like this, its overridden :(
}else{
r= Computerzug(spielfeld.clone(),2,zug);
}
x=r.getlastx();
y=r.getlasty();
if(player){
spielfeld[y][x]=1;
}else{
spielfeld[y][x]=2;
}
}
if(zug<42){
GenAuswerten(zug,player);
zuege+=zug;
}else{
gen--;
}
}
static void GenAuswerten(int zug, boolean win){
for(Runde r: Steps){
r.finishround(win, zug);
ArrayList<Runde> removal = new ArrayList<Runde>();
for(Runde r2 : liste){
if(r2.equal(r.getSpielfeld())){
removal.add(r2);
}
}
for(Runde r3: removal){
liste.remove(r3);
}
}
for(Runde r: Steps){
liste.add(0,r);
}
Steps.clear();
}
you will need to clone the 2nd level arrays when you clone this
r= Computerzug(spielfeld.clone(),1,zug);
so the correct code is
int spielfeldclone[][] = new int[spielfeld.length][];
int i = 0;
for(int[] spielfeldArray: spielfeld){
spielfeldclone[i] =spielfeldArray.clone()lone();
i++;
}
r= Computerzug(spielfeldclone,1,zug);
the reason is that you are doing shallow copy of 2d array
and remeber 2d array is an array of array
normaly clone() of any array would work if the array was of primitive type like int
but here the array you are cloning contain arrays
that mean you will get new references to the same 2nd level array object
So
spielfeld[0] == spielfeld.clone()[0]
is true
since both spielfeld[0] and spielfeld.clone()[0] point to same object
now to resolve that we needed to do shallow copy of the inner arrays each one alone which resulted in deep copy
import.util.Arrays;
public class AList<T> implements ListInterface<T>{
private T[] list;
private int numberOfEntries;
private static final int DEFAILT_INI_CAPACITY=25;
public AList()
{
this(DEFAILT_INI_CAPACIT);
}
public AList
{
numberOfEntries = 0;
// the cast is safe because the new array contains null entries
#SuppressWarnings("unchecked")
T[] tempList = (T[])new Object[initialCapacity];
list = tempList;
}
public void add(T newEntry) {
ensureCapacity();
list[numberOfEntries] = newEntry;
numberOfEntries++;
} // end add
public int getLength() {
return numberOfEntries;
} // end getLength
public boolean isEmpty() {
return numberOfEntries == 0; // or getLength() == 0
} // end isEmpty
public T[] toArray() {
// the cast is safe because the new array contains null entries
#SuppressWarnings("unchecked")
T[] result = (T[])new Object[numberOfEntries];
for (int index = 0; index < numberOfEntries; index++) {
result[index] = list[index];
} // end for
return result;
} // end toArray
Prolbems from Data Strucutre and Algorithum in Java by Frank.
On chapter 13 exercise 12 I'm stuck on the following:
the following method Reduce the size of the array:
private boolean isTooBig()
This method return true if the number if entries in the list is less than half the size of the array and the size of the array is greater than 20.
The second new method creates a new array that is three quarters the size of the current array and then copies the object in the list of the new array:
private void reduceArray()
My Attempt:
private boolean isTooBig()
{
int half = (2 / getLenght());;
return ((numberOfEntries < half) && (numberOfEntries > 20));
}
private void reduceArray()
{
private T[] list2;
stuck...
}
My question: I do not know what is The array that I am reducing.
After I reduce the array. I do not know how to copy an ArrayList to another ArrayList.
Also I am stuck on Main project one.
1) Write a program that thoroughly tests the class AList.
My attempt:
public class test {
public static void main(String[] args)
{
AList<integer> listOfInt = new AList<integer>();
listOfInt.add(1);
listOfInt.add(2);
System.out.println(listOfInt);
}
The output is the address of listOfInt, but I want the literal value 1,2 to be printed.