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");
}
Related
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;
}
}
first of all thank you for looking at my question. My assignment is pretty basic to most but I am an inexperienced programmer. Here is the description of the assignment:
Your objective is to write a class called Storage that can hold a collection of Strings. It must implement the following methods:
addItem(String s) - This method accepts a String parameter and returns a boolean value. The parameter reference is then stored internally in your choice of structure. The method returns true if the reference is successfully added.
getItems() - This method takes no parameters and returns an array containing all the Strings stored in the internal structure. The returned array must not contain any null elements.
isFull() - This method returns true if there is no internal storage available, otherwise false.
removeItem(String s) - This method accepts a String parameter and returns a boolean value. The method must search through the internal storage structure and remove the parameter reference (if present). The method returns true if the reference is successfully removed, otherwise false.
I am completely stumped on most of these. I am using an array to store the data, but I am open to other suggestions. Thanks again.
Alright guys I made a few changes and I started some code, but it won't compile correctly. Based on the description of the methods can someone tell me what I'm doing wrong?
public class Storage {
//variables
private String[] list;
private int size = 10;
private int index = 0;
public boolean addItem(String s) {
for (int i = 0; i < list.length; i++) {
if (!list.equals(null)) {
list[i] = s;
}
}
return true;
}
public String[] getItems() {
for (int i = 0; i < list.length; i++) {
if(!list.equals(null)) {
System.out.println(list[i]);
i++;
}
}
return list;
}
public boolean isFull() {
if (list.length > size) {
System.out.println("The array is full");
}
return true;
}
public boolean removeItem(String s) {
for (int i = index; i < list.length - 1; i++) {
list[i] = list[i + 1];
}
return true;
}
}
addItem(String s): The method should return a boolean value, since you are using an ArrayList, we can use add(Object o), which returns a boolean.
public boolean addItem(String s) {
return list.add(s); // I'm assuming that your instance variable is named list
}
getItems(): Use the method in the ArrayList class called toArray(), passing in an argument of the array type to cast to.
public String[] getItems() {
return list.toArray(new String[list.size()]);
}
isFull(): Not exactly sure what your instructor was asking for here, as an ArrayList will automatically resize, but you could just add an instance variable to your class that contains a maximum size and then check against it like so...
public static final int SIZE = 10;
...
public boolean isFull() {
return list.size() >= SIZE;
}
of course, this means adding code to check that the element you're adding doesn't breach capacity. I'll show this in the complete example below.
removeItem(String s): The remove() method in ArrayList is overloaded to accept an object to remove. Likewise, this method also returns a boolean value.
public boolean removeValue(String s) {
return list.remove(s); // Removes the first occurrence of the string
}
All in all, you should have something similar to the following...
public class Storage {
private ArrayList<String> list = new ArrayList<>();
public static final int SIZE = 10;
public boolean addItem(String s) {
if (isFull())
return false;
return list.add(s);
}
public String[] getItems() {
return list.toArray(new String[list.size()]);
}
public boolean isFull() {
return list.size() >= SIZE;
}
public boolean removeValue(String s) {
return list.remove(s); // Removes the first occurrence of the string
}
}
I want to add an object to my array. I am trying to create a method so whenever it's called, it adds the generic type object. Here's my code:
public class ArrayObjects<E> implements SomeImp<E>{
private E[] list;
private int maxCapacity, currentSize;
public ArrayObjects(){
maxCapacity = 10;
array = (E[]) new Object[maxCapacity];
}
public void addObj(E obj){
array.add(obj); //Throws an error
}
}
Eclipse shows me an error though. It says "Cannot invoke add(E) on the array type E[ ]"
Does anyone know why does this happen? Do you know of an alternative of adding an object to my generic array?
Thank you!
EDIT:
When I create an instance of a class that instantiates ArrayObjects, and try to add a value to it, it doesn't do it. code:
import packageWhereArrayObjectsIs.*;
public class Test {
private ArrayObjects<Integer> list;
public Test() {
list = new ArrayObjects<Integer>();
Test();
}
private void TestOne() {
for(int i=1; i <= 10; i++)
list.addLast(i);
System.out.println("Should print 1 .. 10");
System.out.println(list);
}
}
The method add() does not exist for arrays. You must access array elements using the correct syntax []:
public void addLast(E obj) {
array[currentSize++] = obj;
}
In order for your list to print nicely, you'll want to add a toString() method to your ArrayObjects class:
public String toString() {
return Arrays.toString(array);
}
To iterate over the elements of your ArrayObjects, you can implement the Iterable interface:
public class ArrayObjects<E> implements Iterable<E>
This requires your class to have an iterator() method that returns an Iterator:
public Iterator<E> iterator() {
class It implements Iterator<E>
{
int position = -1;
public boolean hasNext() {
return position + 1 < currentSize;
}
public E next() {
return array[++position];
}
public void remove() {
throw new UnsupportedOperationException();
}
}
return new It();
}
Finally, this code shows how you can now iterate over your list using an enhanced for loop:
ArrayObjects<Integer> list = new ArrayObjects<Integer>();
for (int i = 0; i < 10; i++) list.addLast(i);
for (Integer i: list) {
System.out.println("Iterating over list! Next element is " + i);
}
You should do something like this, assuming that your actual size is 1 when you add your first element BUT the position will be 0 because it's the first position of the array.
public boolean addObj(E obj){
if(actualSize == maxCapacity){
return false;
}
array[actualSize--] = obj;
return true;
}
I changed the return value to return false if there is no positions left in the array (considering that you won't remove any object in the middle).
Why do you need an array? Why not going with a List?
public class ArrayObjects<E> implements SomeImp<E>{
private List<E> list;
private int maxCapacity;
public ArrayObjects(){
maxCapacity = 10;
list = new ArrayList<E>();
}
public boolean addObj(E obj){
if(list.size() == maxCapacity){
return false;
}
list.add(obj);
return true;
}
}
See that using a List you won't have to deal with the actualSize.
EDIT: as Smac89 points out, it makes no sense to use a list. But keep in mind you will have to find an empty position if the array is not full.
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.
Been working on this for a while now and I think I've finally cracked it, it's working for all my tests, but I have a feeling there will be some niggling issues. This is a heavily simplified version of a double sided queue (deque) where every time a value is added, a temporary array is made to store all values, and then the new value appended on. It is easiest to explain this way, I believe. If someone could please just double-check I am correct and there is nothing glaringly wrong here, I would be extremely thankful. Thank you all very much ! :)
public class ArrayBasedDeque<EltType> implements Deque<EltType> {
private final int CAPACITY = 10;
private int capacity;
private int end;
private EltType deque[];
public ArrayBasedDeque() {
this.capacity = CAPACITY;
deque = (EltType[]) (new Object[capacity]);
}
public EltType first() {
return deque[0];
}
public EltType last() {
return deque[end-1];
}
public boolean isEmpty() {
return end == 0;
}
public int size() {
return deque.length;
}
public boolean isFull() {
return end == capacity;
}
public void insertFirst(EltType inserted) {
if (!isEmpty()) {
EltType[] tempArray;
capacity+=1;
tempArray = (EltType[]) new Object[capacity];
for(int i=0;i<end;i++){
tempArray[i+1] = deque[i];
}
deque=tempArray;
}
deque[0] = inserted;
end++;
}
public void insertLast(EltType last) {
if (isFull()){
EltType[] tempArray;
capacity+=1;
tempArray = (EltType[]) new Object[capacity];
for (int i=0;i<end;i++) {
tempArray[i] = deque[i];
}
// System.out.print(deque[end]);
}
deque[end] = last;
end++;
}
public EltType removeFirst() {
EltType[] tempArray;
EltType returned = deque[0];
tempArray = (EltType[]) new Object[capacity];
for (int i=1;i<capacity;i++) {
tempArray[i-1] = deque[i];
}
deque = tempArray;
end--;
return returned;
}
public EltType removeLast() {
EltType[] tempArray;
EltType returned = deque[end-1];
tempArray = (EltType[]) new Object[capacity];
for (int i=0;i<capacity;i++) {
tempArray[i] = deque[i];
}
deque = tempArray;
end--;
return returned;
}
}
A few comments:
I would use T or E as the name of the type parameter, rather than EltType
I'd rename the constant CAPACITY to DEFAULT_CAPACITY, and make it static.
first() will return a value even if the deque is logically empty
last(), removeLast() and removeFirst() should throw an appropriate exception if end is 0
There's no point in having a capacity separate from the size unless you're using that to avoid creating a new array each time. If you're always going to expand/shrink the array on any change, just use the array on its own - you can tell the size just from the array's length
In removeFirst and removeLast your loop bound is capacity instead of end
Use System.arraycopy as a simpler way to copy arrays
You haven't got an assignment to deque in insertLast - hence the exception you're seeing in the comments.
I'm not sure I see the benefit of having this over just using ArrayList<T> though... the main point of having a separate Deque implementation would be to make adding to both head and tail cheap... here we have neither!
... or of course just use ArrayDeque or LinkedList :)
I would suggest
don't create a new Object[] every time you add or remove an entry.
Use System.arrayCopy() instead of manual copy.
You don't need to copy up to the capacity, only up to the end.
you could use a ring buffer to avoid needing to move elements around (no need for copies)
Drop Based from the name ArrayDeque is more consistent with ArrayList, ArrayBlockingQueue, etc.