Inserting into a simple Array and Deleting - java

public class DataOperations {
int arraySize=50;
int[]array=new int[arraySize];
public void generateRandomArray(){
for(int i=0;i<arraySize;i++){
array[i]=i;
}
}
public int getValueAtIndex(int index){
if(index<arraySize){
System.out.println("Your value At index "+index+" is "+array[index]);
return array[index];
}else{
System.out.println("Please Return an Index that is inbounds");
return 0;
}
}
public boolean doesArrayContainValue(int searchValue){
boolean valueInArray=false;
for(int i=0;i<arraySize;i++){
if(array[i]==searchValue){
valueInArray=true;
}
}
return valueInArray;
}
public void deleteIndex(int index){
if(index<arraySize){
for(int i=index;i<(arraySize-1);i++){
array[i]=array[i+1];
}
}
System.out.println(arraySize);
arraySize--;
System.out.println(arraySize);
}
public void printArray(){
for(int i=0;i<arraySize;i++){
System.out.print(i+"-");
System.out.println(array[i]);
}
}
public void insertValue(int index){
if(index<arraySize){
array[arraySize]=index;
System.out.println(arraySize);
arraySize++;
System.out.println(arraySize);
}
}
public void linearSearchForValue(int value){
boolean valueInArray=false;
System.out.println("The was Found and is at Index:");
for(int i=0;i<arraySize;i++){
if(array[i]==value){
System.out.println(i);
}
}
}
}
Hey So I created simple add and delete methods to my array. However, I am unsure about a couple parts. I Understand the add method, and that we are decreasing the arraySize from 50 to 49 for this specific array object that I created in my Driver class below. However, I am not sure why I cannot do my add method before my delete method insertValue method if I put arraySize++ before array[arraySize]=index, and did not call my deleteIndex method shouldnt my arraySize=51? but this throws an out of bounds exception
Driver Class Below
public class Driver {
public static void main(String[] args) {
DataOperations array=new DataOperations();
array.generateRandomArray();
array.insertValue(20);
array.printArray();
}
}

int arraySize=50;
You create an array of size 50. Arrays are of fixed size hence you cannot get an array of size 51. In your code, when adding/deleting an element from the array, you arent changing the size of the array. You are just moving the index to get your desired output. If you want a bigger array you can:
Create a new array of required size and copy all elements from old to new
Use ArrayList instead of arrays.

Related

How would I create a method that stores the parameter value in an array at the index of the position variable, then adds 1 to the position variable

I have an assignment to create an array class where there are 2 constructors where each constructor sets a different size for the array.
The array is already an instance variable along with another instance variable to keep track of the current position in the array.
I have to create a method called add with an integer parameter that will store the parameter value in the array at the index of the position variable, then add 1 to the position variable. If the incremented position variable is outside the bounds of the array, the method calls the addspace method.
The addspace method creates a new array 25% larger than the instance variable array, copies all the values of the instance array to the new array, and assigns the new array to the instance variable.
I also need a method called size that will return the value in the position variable and a method called get that with 1 parameter(an index), the method returns the value at the parameter index.
The last thing I need is a print method that uses a for loop to print the values in the array.
So far this is what I have
public class ArrayClass
{
private int array[];
private int x=0;
public ArrayClass()
{
this.array= new int[10];
add(1);
getThat(0);
print();
}
public ArrayClass(int y)
{
this.array= new int[y];
add(2);
getThat(0);
print();
}
public void add(int a)
{
array[x]=a;
x++;
if(x>array.length)
addspace();
}
public void addspace()
{
double d=array.length+(array.length*0.25);
int v=(int)d;
int newArray[]= new int[v];
for(int i=0; i<array.length; i++)
{
newArray[i]=array[i];
System.out.println(newArray[i]);
}
}
public int size()
{
return x;
}
public int getThat(int index)
{
return array[index];
}
public void print()
{
for(int i=0; i<array.length; i++)
System.out.println(array[i]+" ");
}
public static void main(String[] args)
{
new ArrayClass();
new ArrayClass(5);
}
}
I know the title only asks for help with the first method but if someone would be kind enough to help with the other methods and the reason why my code won't run and print what I want it to that would be much appreciated.
Use the ArrayClass for only for declaring your functionality.Call add method as obj.add(number) until and unless you need to add something inside ArrayClass constructor itself.
Modified these things as per my understanding
In your add method you are assigning the value first and then adding space if the array is full, in this case, you are increasing the size even if it might not be needed (i.e not calling add method again).
Instead of this increase the size only when you require it.
In print function you are iterating through the whole array.Modified to-> it will iterate till the last index of value (i.e x)
package com.example;
public class ArrayClass
{
private int array[];
private int x=0;
private final int DEFAULT_SIZE=4;
public ArrayClass(){
this.array = new int[DEFAULT_SIZE];
}
public ArrayClass(int size){
this.array = new int[size];
}
public void add(int number){
//check whether array have space or not .if not then increase the space.
if(x > this.array.length-1){
addSpace();
}
array[x] =number;
x++;
}
private void addSpace(){
double newSize = array.length + array.length * 0.25;
int tempArray[] = new int[(int) newSize];
for(int i=0; i<array.length; i++){
tempArray[i]=array[i];
}
this.array = tempArray;
}
public int size()
{
return x;
}
public int getThat(int index)
{
return array[index];
}
public void print()
{
//instead of of printing the whole array Printed till last value index.
for(int i=0; i<x; i++)
System.out.println(array[i]+" ");
}
}
From the main method
ArrayClass ac1 = new ArrayClass();
ac1.add(5);
ac1.add(4);
ac1.add(5);
ac1.add(4);
ac1.add(7);
ac1.add(19);
ac1.print();
ArrayClass ac2 = new ArrayClass(5);
ac2.add(1);
//rest of your function call here

Why java.util.ArrayList.remove(int index) is not working properly for the below code?

I was trying to execute the below code. It ran without any compilation errors. But the remove(int index) method is not working as expected.
import java.util.*;
public class Stones {
static int findLastStoneWeight(ArrayList<Integer> weight)
{
while(true)
{
Collections.sort(weight);
int n=weight.size();
if (n==1)
return weight.get(0);
else if(weight.get(n-1)>weight.get(n-2))
{
int temp1=weight.get(n-1);
int temp2=weight.get(n-2);
weight.add(n-2,temp1-temp2);
weight.remove(n-1);
System.out.println(weight.size()); //The new size of weight should be decreased by 1 but it does not!!
}
else
{
weight.remove(n-1);
weight.remove(n-2);
}
}
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
ArrayList<Integer> weight=new ArrayList<Integer>();
System.out.println("Enter the weights:");
while(true)
{
int w=sc.nextInt();
if(w<0)
break;
weight.add(w);
}
int lswt=findLastStoneWeight(weight);
System.out.println("Last stone weight:"+lswt);
}
}
When I used the remove(int index) method on the ArrayList weight the size of the ArrayList should get reduced by 1 but it remains the same. Why?
in the else if branch you noted, you first add an element to the weight ArrayList:
weight.add(n-2,temp1-temp2);
and then remove an element:
weight.remove(n-1);
All in all, you've added an element and removed an element, so the size of the list at the end of the method will be same as it was in the metho'd begining.

Method adding element to array of ints

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

Create a Dynamic Array for Stack structure in Java

I am learning the Stack Data Structure. I want to create a dynamic array. When the size is exceeded, I want to create a new array.
Program output:
java.lang.ArrayIndexOutOfBoundsException: 2
must be :50 40 30
The code is as given below:
class Stack{
int array[];
int size;
int top;
Stack(int size){
this.size=size;
array=new int[size];
top=0;
}
public void push(int a){
if(top>=size){
int array2[]=new int[size*2];
for(int i=0;i<size;i++){
array2[i]=array[i];
}
array[top++]=a;
}
else{
array[top++]=a;
}
}
public int pop(){
return array[--top];
}
}
public class Stack1 {
public static void main(String[] args) {
Stack y=new Stack(2);
y.push(10);
y.push(20);
y.push(30);
y.push(40);
y.push(50);
System.out.println(y.pop());
System.out.println(y.pop());
System.out.println(y.pop());
}
}
You are creating a new array with a doubled size when the original array is full, but then you do nothing with the new array.
Change your code to :
public void push(int a){
if(top>=size){
int array2[]=new int[size*2];
for(int i=0;i<size;i++){
array2[i]=array[i];
}
array = array2;
size *=2;
}
array[top++]=a;
}

Java Queue, entire Queue is replaced by new added element

I am working on a project for school that have jobs(an int array), i am new to Java and have encountered a strange error while trying to put these jobs in a Queue.
My problem is that once i already have one element in the Queue, the next element replaces the previous element in the queue,
i.e if Queue[0] holds arr1, and i add the next element ( Queue.add(arr2)), arr 2 gets added to Queue[1] but Queue also replaces Queue[0] with arr2.
There is a lot of code so i have only posted i am using and where the function where it is called, the element change happens as soon as .add is executed.
public class drumQueue {
private Queue<int[]> myQueue = new LinkedList<int[]>();
private static boolean drumIsBusy = false;
int index=0;
public void add(int[] p){
myQueue.add(p);
}
public void remove(){
myQueue.remove();
}
public int[] getP(){
System.out.println("POPED!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
return myQueue.poll();
}
public boolean isDrumIsBusy() {
return drumIsBusy;
}
public void setDrumIsBusy(boolean drumIsBusy) {
drumQueue.drumIsBusy = drumIsBusy;
}
public void print(){
for( int i =0 ;i < myQueue.size(); i++ ){
System.out.println(myQueue.peek()[1]+ "ELEMENT!!!!!!!!!!!!!!!");
}
}
public int size(){
return myQueue.size();
}
}
Method that uses above class in a different class.
private static void MemeoryManager(int[] a, int[] p) {
// TODO Auto-generated method stub
memoryLink.freeSpaceTableBuilder();
memoryLink.freeSpaceTableBuilder();
p[2] = memoryLink.addressFinder(p[3]);
memoryLink.addTooMemory(p[2],p[3],p[1]);
memoryLink.merge();
drumQueue.add(p);
Swap(a,0);
}
I think you class store data in proper way, but it have a problem in print() method. peek() always return head of the queue, so you just print first element size() times. Try to use queue.toArray() for printing purposes

Categories