Shifting an array after removing a value (Java) - java

I made a program that makes an array of random ints and doubles in size if the user tries to add an int. Example: 1|2|3|4 if they were to add another int it would look like 1|2|3|4|5|0|0|0. I have made a method to add an int which works but now I am trying to make methods that remove one of a certain int and another that removes all of a certain int. for example removeInt(3) would give me 1|2|0|4|5|0|0|0. I have the first part working so that it shifts the zero to the end like this 1|2|4|5|0|0|0|0 but cannot get it to work for more than one of the same value. Any suggestions?
// ****************************************************************
// IntegerList.java
//
// Define an IntegerList class with methods to create & fill
// a list of integers.
//
// ****************************************************************
public class IntegerList
{
int[] list; //values in the list
//-------------------------------------------------------
//create a list of the given size
//-------------------------------------------------------
public IntegerList(int size)
{
list = new int[size];
}
//-------------------------------------------------------
//fill array with integers between 1 and 100, inclusive
//-------------------------------------------------------
public void randomize()
{
for (int i=0; i<list.length; i++)
list[i] = (int)(Math.random() * 100) + 1;
}
//-------------------------------------------==----------
//print array elements with indices
//-------------------------------------------------------
public void print()
{
for (int i=0; i<list.length; i++)
System.out.println(i + ":\t" + list[i]);
}
public void addElement(int newVal){
boolean full = true;
System.out.println(list.length);
int position = 0;
int place;
while(position < list.length){
System.out.println("HERE");
if(list[position]==0){
System.out.println("here");
full = false;
place = position;
System.out.println(place);
}
position = position+1;
}
if(full == true){
list = increaseSize(list);
System.out.println("L"+list.length);
full = false;
}
for(int i = 0;i<list.length;i++){
if(list[i]==0){
if(i<position){
position = i;
System.out.println(list.length);
}
}
}
list[position] = newVal;
}
public void removeFirst(int newVal){
int position = 0;
boolean removed = false;
for(int i = 0; i<list.length;i++){
if(list[i] == newVal){
list[i]=0;
position = i;
removed = true;
break;
}
}
if(removed==true){
for(int i = position;i<list.length;i++){
if(i!=list.length-1){
list[i]=list[i+1];
}
}
list[list.length-1]= 0;
}
}
public void removeAll(int newVal){
int position = 0;
boolean removed = false;
for(int i = 0; i<list.length;i++){
if(list[i] == newVal){
list[i]=0;
position = i;
removed = true;
}
}
if(removed==true){
for(int i = 0;i<list.length;i++){
if(i!=list.length-1 && list[i+1]==newVal){
list[i]=0;
}
if(list[i]==newVal){
list[i]=0;
}
}
}
}
public static int[] increaseSize(int[] x){
int newLength = x.length *2;
int[] newx = new int[newLength];
for(int i = 0; i<x.length; i++){
newx[i] = x[i];
}
return newx;
}
public static int[] halfSize(int[] x){
int[] newx = new int[x.length / 2];
for(int i = 0; i<x.length; i++){
newx[i] = x[i];
}
return newx;
}
}

I believe there's an easier way to implement your removeAll method. Move 2 (rather than 1) indices through your array constantly shifting the values over the items you are removing;
int dest = 0;
int source = 0;
while (source < array.length) {
if (array[dest] != valueToRemove)
dest++;
array[dest] = array[source++];
}
while (dest < array.length) {
array[dest++] = 0;
}

I executed your code and found out that the problem is in this piece, under removeAll()...
if(removed){
for(int i = 0;i<list.length;i++){
if(i!=list.length-1 && list[i+1]==newVal){
list[i]=0;
}
if(list[i]==newVal){
list[i]=0;
}
}
}
If you comment out and try once, you will see the removeAll() is working and your desired number is replaced with 0s. Now why you don't simply check your numbers and shift(sorting), if they are greater than 0 to the left?

Related

How can I make a new Array and copy all the postive elements from the other array in the new array and return it?

This method returns an array that contains the positive elements of the parameter array in.
To do that, compute the number of positive elements in the array in and store the obtained value in the variable
nElements of type integer, declare the double array output of size nElements, copy the positive elements
of in into the array output, and return the array output. If all the elements of the array in are non-positive,
your method should return an array of size 1 and the only element of the returned array is assigned the
value -1.
My question here is when I run my program it states Exception in thread "main" java.lang.NegativeArraySizeException and I don't know how to take it out and only return the positive elements.
The Java-Code:
public static double [] partialPositiveArray(double [] in)
{
int nElements = 0;
for(int i = 0; i < in.length; i++)
{
if(in[i] > 0)
{
nElements = (int)in[i];
}
else if(in[i] <= 0)
{
nElements = -1;
}
}
double [] output = new double[nElements];
for(int i = 0; i < in.length; i++)
{
output[i] = nElements;
}
return output;
}
with this code you will add all positive numbers. the sum in this example is 60.7 and for all negative numbers it will write -1 in the negative-array. in this example twice.
Code:
public class NegativeAndPositiveNumbers {
public static void main(String[] args) {
double[] arr = {25.0, -7.0, 10.7, 25.0, -64.0};
System.out.println(partialPositiveArray(arr));
int negative[] = negativeArray(arr);
for (int i = 0; i < negative.length; i++){
System.out.print(negative[i] + " ");
}
}
public static double partialPositiveArray(double[] in) {
double nElements = 0;
for (int i = 0; i < in.length; i++) {
if (in[i] > 0) {
nElements += in[i];
}
}
return nElements;
}
public static int[] negativeArray(double[] in) {
int[] negativeWithZero = new int[in.length];
int index = 0;
for (int i = 0; i < in.length; i++) {
if (in[i] <= 0) {
negativeWithZero[index] = -1;
index++;
}
}
int[] negative = new int[index];
for (int j = 0; j < negative.length; j++){
negative[j] = negativeWithZero[j];
}
return negative;
}
}
I think it could be solved more easily, but it works anyway. I hope everything is clear
public static double [] partialPositiveArray(double [] in) {
return Arrays.stream(in)
.filter(d -> d > 0)
.toArray();
}
You are changing the variable nElements when it is positive you are taking the value from in[ ] array and when it is negative you are changing it to -1.
for(int i = 0; i < in.length; i++)
{
if(in[i] > 0)
{
nElements = (int)in[i];
}
else if(in[i] <= 0)
{
nElements = -1;
}
}
In the array you are passing to the function there seems to be a negative number at end so when control comes across this ,nElements value is -1. After the loop you are instantiating an array with size given as this variable
double [] output = new double[nElements];
Therefore you are getting NegativeArrayIndexException
Solution as per requirement:
public static double [] partialPositiveArray(double [] in)
{
boolean gotPositive=false;
int size=0;
int j=0;
for(int i = 0; i < in.length; i++)
{
if(in[i] >= 0)
{
size++;
gotPositive=true;
}
}
if(size==0 && !gotPositive){
size=1;
}
double [] output = new double[size];
for(int i = 0; i < in.length; i++)
{
if(in[i] >= 0)
{
output[j++]=in[i];
}
}
if(!gotPositive){
output[0]=-1;
}
return output;
}

MinMaxAI checkers implementation

I can't seem to get my min max AI to work. This is the code so far. I get an error saying my allScores array is empty so it won't set my move to the bestScored move. Any help would be appreciated.
int[] move;
public static int makeMove(Board board, int currentPlayerColor, int maxingPlayerColor){
int score = 0;
int[] moveIndex={};
if (Rules.gameOver(board)[0]==1){
if(Rules.gameOver(board)[1] == maxingPlayerColor){
System.out.println("1");
return score = 1;
} else if(Rules.gameOver(board)[1] == Math.abs(maxingPlayerColor-1)) {
System.out.println("-1");
return score = -1;
} else{
System.out.println("0");
return score = 0;
}
} else {
int[][] availableMoves = board.availableMoves(board, currentPlayerColor);
int[] allScores = {};
System.out.println("loop length: "+ availableMoves.length);
for(int x = 0; x<availableMoves.length; x++){
Board temp = board;
if(currentPlayerColor == maxingPlayerColor){
Board.doMove(availableMoves[x], temp, 7);
} else {
Board.doMove(availableMoves[x], temp, 0);
}
System.out.println(""+x);
allScores = add(makeMove(temp,Math.abs(maxingPlayerColor-1), maxingPlayerColor), allScores);
System.out.println("allscore len "+ allScores.length);
}
if(currentPlayerColor == maxingPlayerColor){
for(int x = 0; x<allScores.length; x++){
if(score < allScores[x]){
allScores = add(score, allScores);
}
}
for(int x = 0; x<allScores.length; x++){
if(score == allScores[x]){
moveIndex = add(x,moveIndex);
}
}
System.out.println("max "+moveIndex.length);
move = availableMoves[rand.nextInt(moveIndex.length)];
} else {
for(int x = 0; x<allScores.length; x++){
if(score > allScores[x]){
score = allScores[x];
}
}
for(int x = 0; x<allScores.length; x++){
if(score == allScores[x]){
moveIndex = add(x,moveIndex);
}
}
System.out.println("min "+moveIndex.length);
move = availableMoves[rand.nextInt(moveIndex.length)];
}
}
return 0;
}
You're trying to add elements onto an array with
allScores = add(...
But that isn't how it works. You can't actually add elements onto an array, you can only change existing elements.
So when you make the array, you have this:
int[] allScores = {};
But that creates an empty array and you can't do anything with that. Instead, declare it like this:
int[] allScores = new int[SIZE];
Replacing SIZE with the number of elements you want the array to hold.
Then you can access and change certain elements like this:
allScores[index] = someNumber;
There are also some formatting and syntax errors. Try using a text editor or IDE that includes syntax highlighting to find easy mistakes.
Also read over this guide to learn about arrays.

Core Java Practical Questions

A Test array has the following property:
a[0] = a[1] + a[2] = a[3] + a[4] + a[5] = a[6] + a[7] + a[8] + a[9] = ...
The length of a Test array must be n*(n+1)/2 for some n.
Write a method named isTestArray that returns 1 if its array argument is a Test array, otherwise it returns 0. The function signature is:
int isMadhavArray(int[ ] a)
Example:
This is what I have tried:
public class TestArray {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(isTestArray(new int[] {2,1,1,4,-1,-1}));
}
static int isTestArray(int[] a){
boolean isEq=true;
for(int i=0;i<a.length;i++){
int n=i, value=a.length;
int equation=n*(n+1)/2;
if(value==equation)
{
for(int x=0,y=1;y<a.length;x++,y++){
if(a[0]==a[x]+a[y]){
//having problem over here :(
}
}
}
else
isEq=false;
}
if(isEq)
return 1;
else
return 0;
}
}
Number of elements in sum increases by 1 in every portion.
You should do 2 things:
Write a method that will calculate sum of N elements starting from K position in array
Increment i with the number of the smallest portion in iteration
example code:
int portionSize = 1; // number of elements to sum
int position = 0; // index of first element
while (position + 2 * portionSize + 1 < array.length) { // condition for last iteration
if (sum(position, portionSize) != sum(position + portionSize, portionSize + 1) {
return false; // if not equal, return immediately
}
position += portionSize;
portionSize++;
}
Here is my attempt for your troubling inner for loop. Because each time you loop, you increment the number of indexes you need to add by one, so I think you need another nested loop like this. I know it is ugly. Can't blame me, I am a beginner.
public class TestArray {
public static void main(String[] args) {
System.out.println(isTestArray(new int[] {2,1,1,4,-1,-1}));
}
static int isTestArray(int[] a) {
boolean isEq = false;
for(int i=0; i < a.length; i++) {
int n=i, value = a.length;
int equation= n*(n+1)/2;
if (value==equation) {
int index = 1;
for (int x = 1; x < a.length; x++) {
int total = 0;
for (int y = index, count = 0; count < x+1; y++, count++) {
if (y!= a.length) {
total += a[y];
if (total == a[0])
isEq = true;
else
isEq = false;
index++;
}
else
break;
}
}
}
}
if (isEq)
return 1;
else
return 0;
}
public class TestArray {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(isTestArray(new int[] {2,1,1}));
System.out.println(isTestArray(new int[] {3, 1, 2, 3, 0}));
}
static int isTestArray(int[] a){
boolean isEq=false, isEx=false;
int equation=0,value=a.length;
//for equation check
for(int n=0;n<value;n++){
equation=n*(n+1)/2;
if(value==equation){
isEx=true;
break;
}
}
//if equation is true
if(isEx)
{
int x=1,y=3,c=0,sum=0;
do{
for(int I=x,J=y;I<J;I++){
sum=sum+a[I];
}
if(a[0]==sum){
isEq=true;
sum=0;
}
else{
isEq=false;
break;
}
c++;
x=y;
y=x+2+c;
}while(x<a.length);
}
//last operation of return
if(isEq)
return 1;
else
return 0;
}
}
import java.io.*;
public class StackQues1{
static boolean flag = true;
static int arrLength = 0;
public static void main(String args[]){
Console c = System.console();
System.out.println("Enter the length of array - ");
arrLength = Integer.parseInt(c.readLine());
//Let max val of n<=20
//To check n(n+1)/2
boolean nFlag = false;
for(int n=1;n<=20;n++){
if(arrLength == (n*(n+1))/2){
nFlag = true;
}
}
if(!nFlag){
System.out.println("Length of array is not in the form of (n*(n+1))/2");
}else{
int arr[] = new int[arrLength];
System.out.println("Enter the elements of array - ");
for(int i=0;i<arr.length;i++){
arr[i] = Integer.parseInt(c.readLine());
}
System.out.println("Returned value = "+isTestArray(arr));
}
}
//Logic Implementation
public static int isTestArray(int[] arr){
int sum = 0;
int noOfElements=0;
for(int i=0;i<arr.length;){
noOfElements++;
sum=0;
for(int j=1;j<=noOfElements;j++){
sum=sum+arr[i];
i++;
}
if(arr[0] == sum){
flag = true;
}else{
flag = false;
break;
}
}
if(flag){
return 1;
}else{
return 0;
}
}
}

How can I find the smallest covering prefix of an array in Java?

Find the first covering prefix of a given array.
A non-empty zero-indexed array A consisting of N integers is given. The first covering
prefix of array A is the smallest integer P such that and such that every value that
occurs in array A also occurs in sequence.
For example, the first covering prefix of array A with
A[0]=2, A[1]=2, A[2]=1, A[3]=0, A[4]=1 is 3, because sequence A[0],
A[1], A[2], A[3] equal to 2, 2, 1, 0 contains all values that occur in
array A.
My solution is
int ps ( int[] A )
{
int largestvalue=0;
int index=0;
for(each element in Array){
if(A[i]>largestvalue)
{
largestvalue=A[i];
index=i;
}
}
for(each element in Array)
{
if(A[i]==index)
index=i;
}
return index;
}
But this only works for this input, this is not a generalized solution.
Got 100% with the below.
public int ps (int[] a)
{
var length = a.Length;
var temp = new HashSet<int>();
var result = 0;
for (int i=0; i<length; i++)
{
if (!temp.Contains(a[i]))
{
temp.Add(a[i]);
result = i;
}
}
return result;
}
I would do this
int coveringPrefixIndex(final int[] arr) {
Map<Integer,Integer> indexes = new HashMap<Integer,Integer>();
// start from the back
for(int i = arr.length - 1; i >= 0; i--) {
indexes.put(arr[i],i);
}
// now find the highest value in the map
int highestIndex = 0;
for(Integer i : indexes.values()) {
if(highestIndex < i.intValue()) highestIndex = i.intValue();
}
return highestIndex;
}
Your question is from Alpha 2010 Start Challenge of Codility platform. And here is my solution which got score of 100. The idea is simple, I track an array of counters for the input array. Traversing the input array backwards, decrement the respective counter, if that counter becomes zero it means we have found the first covering prefix.
public static int solution(int[] A) {
int size = A.length;
int[] counters = new int[size];
for (int a : A)
counters[a]++;
for (int i = size - 1; i >= 0; i--) {
if (--counters[A[i]] == 0)
return i;
}
return 0;
}
here's my solution in C#:
public static int CoveringPrefix(int[] Array1)
{
// Step 1. Get length of Array1
int Array1Length = 0;
foreach (int i in Array1) Array1Length++;
// Step 2. Create a second array with the highest value of the first array as its length
int highestNum = 0;
for (int i = 0; i < Array1Length; i++)
{
if (Array1[i] > highestNum) highestNum = Array1[i];
}
highestNum++; // Make array compatible for our operation
int[] Array2 = new int[highestNum];
for (int i = 0; i < highestNum; i++) Array2[i] = 0; // Fill values with zeros
// Step 3. Final operation will determine unique values in Array1 and return the index of the highest unique value
int highestIndex = 0;
for (int i = 0; i < Array1Length; i++)
{
if (Array2[Array1[i]] < 1)
{
Array2[Array1[i]]++;
highestIndex = i;
}
}
return highestIndex;
}
100p
public static int ps(int[] a) {
Set<Integer> temp = new HashSet<Integer>();
int p = 0;
for (int i = 0; i < a.length; i++) {
if (temp.add(a[i])) {
p = i+1;
}
}
return p;
}
You can try this solution as well
import java.util.HashSet;
import java.util.Set;
class Solution {
public int ps ( int[] A ) {
Set set = new HashSet();
int index =-1;
for(int i=0;i<A.length;i++){
if(set.contains(A[i])){
if(index==-1)
index = i;
}else{
index = i;
set.add(A[i]);
}
}
return index;
}
}
Without using any Collection:
search the index of the first occurrence of each element,
the prefix is the maximum of that index. Do it backwards to finish early:
private static int prefix(int[] array) {
int max = -1;
int i = array.length - 1;
while (i > max) {
for (int j = 0; j <= i; j++) { // include i
if (array[i] == array[j]) {
if (j > max) {
max = j;
}
break;
}
}
i--;
}
return max;
}
// TEST
private static void test(int... array) {
int prefix = prefix(array);
int[] segment = Arrays.copyOf(array, prefix+1);
System.out.printf("%s = %d = %s%n", Arrays.toString(array), prefix, Arrays.toString(segment));
}
public static void main(String[] args) {
test(2, 2, 1, 0, 1);
test(2, 2, 1, 0, 4);
test(2, 0, 1, 0, 1, 2);
test(1, 1, 1);
test(1, 2, 3);
test(4);
test(); // empty array
}
This is what I tried first. I got 24%
public int ps ( int[] A ) {
int n = A.length, i = 0, r = 0,j = 0;
for (i=0;i<n;i++) {
for (j=0;j<n;j++) {
if ((long) A[i] == (long) A[j]) {
r += 1;
}
if (r == n) return i;
}
}
return -1;
}
//method must be public for codility to access
public int solution(int A[]){
Set<Integer> set = new HashSet<Integer>(A.length);
int index= A[0];
for (int i = 0; i < A.length; i++) {
if( set.contains(A[i])) continue;
index = i;
set.add(A[i]);
}
return index;
}
this got 100%, however detected time was O(N * log N) due to the HashSet.
your solutions without hashsets i don't really follow...
shortest code possible in java:
public static int solution(int A[]){
Set<Integer> set = new HashSet<Integer>(A.length);//avoid resizing
int index= -1; //value does not matter;
for (int i = 0; i < A.length; i++)
if( !set.contains(A[i])) set.add(A[index = i]); //assignment + eval
return index;
}
I got 100% with this one:
public int solution (int A[]){
int index = -1;
boolean found[] = new boolean[A.length];
for (int i = 0; i < A.length; i++)
if (!found [A[i]] ){
index = i;
found [A[i]] = true;
}
return index;
}
I used a boolean array which keeps track of the read elements.
This is what I did in Java to achieve 100% correctness and 81% performance, using a list to store and compare the values with.
It wasn't quick enough to pass random_n_log_100000 random_n_10000 or random_n_100000 tests, but it is a correct answer.
public int solution(int[] A) {
int N = A.length;
ArrayList<Integer> temp = new ArrayList<Integer>();
for(int i=0; i<N; i++){
if(!temp.contains(A[i])){
temp.add(A[i]);
}
}
for(int j=0; j<N; j++){
if(temp.contains(A[j])){
temp.remove((Object)A[j]);
}
if(temp.isEmpty()){
return j;
}
}
return -1;
}
Correctness and Performance: 100%:
import java.util.HashMap;
class Solution {
public int solution(int[] inputArray)
{
int covering;
int[] A = inputArray;
int N = A.length;
HashMap<Integer, Integer> map = new HashMap<>();
covering = 0;
for (int i = 0; i < N; i++)
{
if (map.get(A[i]) == null)
{
map.put(A[i], A[i]);
covering = i;
}
}
return covering;
}
}
Here is my Objective-C Solution to PrefixSet from Codility. 100% correctness and performance.
What can be changed to make it even more efficient? (without out using c code).
HOW IT WORKS:
Everytime I come across a number in the array I check to see if I have added it to the dictionary yet.
If it is in the dictionary then I know it is not a new number so not important in relation to the problem. If it is a new number that we haven't come across already, then I need to update the indexOftheLastPrefix to this array position and add it to the dictionary as a key.
It only used one for loop so takes just one pass. Objective-c code is quiet heavy so would like to hear of any tweaks to make this go faster. It did get 100% for performance though.
int solution(NSMutableArray *A)
{
NSUInteger arraySize = [A count];
NSUInteger indexOflastPrefix=0;
NSMutableDictionary *myDict = [[NSMutableDictionary alloc] init];
for (int i=0; i<arraySize; i++)
{
if ([myDict objectForKey:[[A objectAtIndex:i]stringValue]])
{
}
else
{
[myDict setValue:#"YES" forKey:[[A objectAtIndex:i]stringValue]];
indexOflastPrefix = i;
}
}
return indexOflastPrefix;
}
int solution(vector &A) {
// write your code in C++11 (g++ 4.8.2)
int max = 0, min = -1;
int maxindex =0,minindex = 0;
min = max =A[0];
for(unsigned int i=1;i<A.size();i++)
{
if(max < A[i] )
{
max = A[i];
maxindex =i;
}
if(min > A[i])
{
min =A[i];
minindex = i;
}
}
if(maxindex > minindex)
return maxindex;
else
return minindex;
}
fwiw: Also gets 100% on codility and it's easy to understand with only one HashMap
public static int solution(int[] A) {
// write your code in Java SE 8
int firstCoveringPrefix = 0;
//HashMap stores unique keys
HashMap hm = new HashMap();
for(int i = 0; i < A.length; i++){
if(!hm.containsKey(A[i])){
hm.put( A[i] , i );
firstCoveringPrefix = i;
}
}
return firstCoveringPrefix;
}
I was looking for the this answer in JavaScript but didn't find it so I convert the Java answer to javascript and got 93%
function solution(A) {
result=0;
temp = [];
for(i=0;i<A.length;i++){
if (!temp.includes(A[i])){
temp.push(A[i]);
result=i;
}
}
return result;
}
// you can also use imports, for example:
import java.util.*;
// you can use System.out.println for debugging purposes, e.g.
// System.out.println("this is a debug message");
class Solution {
public int solution(int[] A) {
// write your code in Java SE 8
Set<Integer> s = new HashSet<Integer>();
int index = 0;
for (int i = 0; i < A.length; i++) {
if (!s.contains(A[i])) {
s.add(A[i]);
index = i;
}
}
return index;
}
}

Java: Expanding array size, can't seem to keep all values in original locations

For my current homework, I'm trying to sort my array through a generic class as the user inserts values into its locations. When the size reads as fully loaded, the array class calls in an expansion method that increases the size of the array while retaining its values in proper locations, which I followed from my Professor's note. For some reason, all my values except for location[0] seem to either be misplaced or erased from the array. I'm leaning that the problem originates in the expansion method but I have no idea how to fix this.
For example, the initial size is currently set to 5 but increments by 3 when expansion method is called. The user can input values 1,2,3,4,5 perfectly. But expansion is called when user inputs new value 6 that outputs an array of 1, 6, null, null, null, null. Any further will lead to the error "Exception in thread "main" java.lang.NullPointerException"
Here is my Sorted Array class:
public class SortedArray {
private int size;
private int increment;
private int top;
Comparable[] a;
public SortedArray(int initialSize, int incrementAmount)
{
top = -1;
size = initialSize;
increment = incrementAmount;
a = new Comparable [size];
}
public int appropriatePosition(Comparable value)
{
int hold = top;
if(hold == -1)
{
hold = 0;
}
else
{
for(int i = 0; i <= top; i++)
{
if(value.compareTo(a[i]) > 0)
{
hold = i + 1;
}
}
}
return hold;
}
public Comparable smallest()
{
return a[0];
}
public Comparable largest()
{
return a[top];
}
public void insert(Comparable value)// the method that my driver calls for.
{
int ap = appropriatePosition(value);
//Expansion if full
if(full() == true)
{
expansion();
}
//Shifting numbers to top
for(int i = top; i >= ap ; i--)
{
{
a[i + 1] = a[i];
}
}
a[ap] = value;
top++;
}
public boolean full()
{
if(top == a.length -1)
{
return true;
}
else
{
return false;
}
}
public void expansion()//here's where the expansion begins
{
int newSize = a.length + increment;
Comparable[] tempArray = new Comparable[newSize];
for(int i= 0; i < a.length; i++)
{
tempArray[i]= a[i];
a = tempArray;
}
}
Here's my driver class that calls for the insert method in SortedArray class.
public class IntDriver {
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
//Creating variables
int data;
boolean check = false;
int choice;
int size = 5;
int increment = 3;
SortedArray b = new SortedArray(size, increment);
//Creating Menu
System.out.println("Please choose through options 1-6.");
System.out.println("1. Insert\n2. Delete\n3. Clear\n4. Smallest\n5. Largest\n6. Exit\n7.Redisplay Menu");
while(check == false)
{
choice = keyboard.nextInt();
switch(choice)
{
case 1:
System.out.println("Type the int data to store in array location.");
data = keyboard.nextInt();
Integer insertObj = new Integer(data);
b.insert(insertObj);
System.out.println("The value " + data + " is inserted");
b.print();
break;
In the expansion method, you're replacing a too soon. The replacement should happen after the for loop:
public void expansion()//here's where the expansion begins
{
int newSize = a.length + increment;
Comparable[] tempArray = new Comparable[newSize];
for(int i= 0; i < a.length; i++)
{
tempArray[i]= a[i];
}
a = tempArray;
}

Categories