reset password
Author Message
Amedrano
Posts: 80
Posted 20:30 Nov 28, 2013 |

I'm trying to remove an element from an array, but it only gets replaced by the last element and the array remains the same size.  Any help would be appreciated.

 

 

import java.util.*;


public class Practice
{
    public static void main(String[] args)
    {  
        double[] values = {8, 7, 8.5, 9.5, 7, 4, 10};
        double smallest = values[0];
        int currentSize = values.length;
        int pos = 0;
        boolean found = false;
          
        for (int i = 1; i < values.length; i++)
        {
            if (values[i] < smallest)
            {
                smallest = values[i];
            }
        }
        System.out.println(smallest);
        System.out.println();
        while (pos < values.length && !found)
        {
            if (values[pos] == smallest)
            {
               found = true;
            }
            else
            {
                pos++;
            }
        }
        
        if (found = true)
        {
            System.out.println("Found at position: " + pos);
        }
        
        else
        {
            System.out.println("Not found");
        }
        System.out.println();
        
        values[pos] = values[currentSize - 1];
        currentSize--;
        
        double total = 0;
        for (double element : values)
        {
            total = total + element;
        }
        double avg = 0;
        if (values.length > 0)
        {
            avg = total / values.length;
        }
        System.out.println(total);
        System.out.println();
        
        System.out.println(avg);
        System.out.println();
        
        for (int i = 0; i < values.length; i++)
        {
            System.out.println(values[i]);
        }
        
    }
}

 

Last edited by Amedrano at 20:30 Nov 28, 2013.
hal255
Posts: 51
Posted 21:18 Nov 28, 2013 |

Line 35, I think you need to change it to --->  if (found == true)

if (found = true) will always assign found to be true.

But to answer your question, Line 65, I changed the for loop statement to ---> for (int i = 0; i < currentSize; i++)

in your program, currentSize was decremented by 1, but value.length was still same throughout the program.

Amedrano
Posts: 80
Posted 21:46 Nov 28, 2013 |

I thought the point of learning to remove an element from an array was to learn to change the number of values in that array.  Does the array still have the same size after this?  For example, the array i started with had 7 values.  Does it still  have 7 and we are not showing them  or 6 values?

rabbott
Posts: 1649
Posted 22:00 Nov 28, 2013 |

ArrayLists vary in size. Arrays always have the same size (length).  A partially filled array has fewer elements assigned than the capacity of the array. But the array itself is fixed in its length. Some of the array positions may not be used, but they are still there.