Hello,
I am working on the problem.
Here is the wording:
6) Specify, design and implement a class that can store an array of integer. The number of Maximum element can be 100. Write methods to :
a. Add an integer at the beginning of the array
b. Add an integer at the end of the array
c. Remove an integer at the beginning of the array
d. Remove an integer at the end of the array
e. Insert an integer at any location except beginning and end
f. Remove an integer at any location except beginning and end
I am currently working on a and b.
I keep getting "outofbound" exception, which I can't resolve.
Can you help?
here is my code
Main//
import java.io.*;
public class ArrayMain {
public static void main(String[] args) throws IOException
{
BufferedReader stdin = new BufferedReader(new InputStreamReader( System.in ) );
int a = 0;
int b = 0;
String temp;
ArrayC c = new ArrayC();
System.out.println("Enter the size of the array so it can be filled: ");
temp = stdin.readLine();
a = Integer.parseInt( temp ); // convert inS to int using wrapper classes
System.out.println("Enter an integer number that will be allocated to the approprite place in the array: ");
temp = stdin.readLine();
b = Integer.parseInt( temp ); // convert inS to int using wrapper classes
c.addAtBegin(a, b);
c.addAtEnd(a, b);
}
}
//CLASS
public class ArrayC
{
// instance variables
// private int b [];
private int a;
private int a1;
final int MAX_VAL = 100;
/**
* Constructor class StoreArray
*/
public ArrayC()
{
a = 0;
a1 = 0;
//b = new int [99];
}
public void addAtBegin(int n, int m) // adding an integer at the beginning of the array
{
a = n;
a1 = m;
int i;
if (a <= MAX_VAL)
{
int [] b = new int [a];
for (i = 0; i < b.length; i++)
b[i] = i;
// System.out.println("test display:" + b[i]);
for(i = a; i >= 0; i--) // move all the integers by one
b[i+1] = b[i];
b[0] = a1;
for (i =0; i < b.length; i++)
System.out.println("All Values of the Array including the new added value is: ");
System.out.println(+ b[i]);
}
else
{
System.out.println("Error");
}
}
public void addAtEnd(int n, int m) // adding an integer at the End of the array
{
a = n;
// input desirable number of integers into array
if (a <= MAX_VAL)
{
int [] b = new int [100];
int i;
for (i = 0; i < a; i++)
b[i] = i;
System.out.println("test display:" + b[i]); // just a testing but need to learn how to display all the values though
// Now, input integer the integer to the end of an array
a1 = m;
b[i+1] = a1;
/* move all the integers by one
for(i= a; i>= a+1; i++)
b[i+1] = b[i];
b[a] = a1; */
System.out.println("test value of the last element " + b[i+1]);
}
else
{
System.out.println("Error");
}
}
}
P.S. I know where the problem is but can't figure out a way to fix it. I even tried counting the loop and it seems to be perfectly fine.