jzbakos jzbakos - 1 month ago 8
Java Question

Removing elements from a 'full' array

This is a little assignment I am working on. I am a beginner Java programmer and have ran into an issue during this little program. For some reason, if the array contains 10 elements, the removal method does not work. I would love some advice/help in regards to fixing this issue.

When the array contains 10 elements, and I attempt to remove one, the arrangement of the elements in the textArea is not what it should be. Everything should shift over 1, containing 9 elements, with the last element as 0. When an element is removed, all the elements should adjust themselves and shift to the left.

The default appearance of the output is: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

If I enter the numbers 1 - 10, the output should look like this:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

If the user attempts remove the last element, it will set it to 0:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

However, if the user attempts to remove another element, lets say 5, the program throws an out of bounds exception in the console. If they remove 5, the output should be: [1, 2, 3, 4, 6, 7, 8, 9, 10, 0]

For more context, here are the assignment details:


Create a complete program that has the ability to store and display integer values in an array. The maximum number of values that your program should be able to handle is 10.


  • Add additional elements to the array using screen input (textbox and button).

  • Remove array elements based on screen input (textbox and button).

  • List all of the elements in the array and compute the sum of all the elements.

  • List the even elements in the array and compute the sum of the even elements.

  • List the odd elements in the array and compute the sum of the odd elements.




import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;

public class SumElement implements ActionListener {

public static JButton add, remove, sumAll, sumEven, sumOdd;
public static JTextField inputField;
public static JTextArea textArea;
public static int counter = 0;
public static int[] numbers = new int[10];
public static JLabel titleText;

public static void main(String[] args) {
System.out.println("Counter: " + counter);

// Frame
JFrame frame = new JFrame("Integer Sums");
frame.setSize(178, 240);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Container panel
JPanel container = new JPanel();
container.setLayout(new BoxLayout(container, BoxLayout.PAGE_AXIS));
frame.setContentPane(container);

// Title panel
JPanel titlePane = new JPanel();
titleText = new JLabel("Integer Sums");

// Content panel
JPanel content = new JPanel();
content.setPreferredSize(new Dimension(300, 180));
content.setLayout(null);

// Buttons
add = new JButton("Add");
add.setBounds(4, 50, 80, 20);
add.addActionListener(new SumElement());

remove = new JButton("Remove");
remove.setBounds(88, 50, 80, 20);
remove.addActionListener(new SumElement());

sumAll = new JButton("Sum All");
sumAll.setBounds(4, 74, 164, 20);
sumAll.addActionListener(new SumElement());

sumEven = new JButton("Sum Even");
sumEven.setBounds(4, 98, 164, 20);
sumEven.addActionListener(new SumElement());

sumOdd = new JButton("Sum Odd");
sumOdd.setBounds(4, 122, 164, 20);
sumOdd.addActionListener(new SumElement());

// Text area, and text field
inputField = new JTextField();
inputField.setBounds(4, 21, 164, 25);

JLabel inputLabel = new JLabel("Input integer value below:");
inputLabel.setBounds(12, 6, 164, 13);

textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setBounds(4, 144, 165, 36);

// Adding everything
container.add(titlePane);
titlePane.add(titleText);
container.add(content);
content.add(inputLabel);
content.add(inputField);
content.add(scrollPane);
content.add(add);
content.add(remove);
content.add(sumAll);
content.add(sumEven);
content.add(sumOdd);

// Extras
frame.toFront();
frame.setVisible(true);
}

public void actionPerformed(ActionEvent event) {
if (event.getActionCommand().equals("Add")) {
if (counter == 10) {
titleText.setText("Error: too many values");
} else {
numbers[counter] = Integer.parseInt(inputField.getText());
textArea.setText(Arrays.toString(numbers));
counter++;
}
System.out.println("Counter: " + counter);
} else if (event.getActionCommand().equals("Remove")) {
for (int i = 0; i < counter; i++) {
if (Integer.parseInt(inputField.getText()) == numbers[i]) {
for (int x = i; x < counter - 1; x++) {
numbers[x] = numbers[x + 1];
}
textArea.setText(Arrays.toString(numbers));
counter--;
} else {
titleText.setText("Error: value doesn't exist");
}
}
System.out.println("Counter: " + counter);
} else if (event.getActionCommand().equals("Sum All")) {
int sum = 0;
for (int i = 0; i <= counter; i++) {
sum += numbers[i];
}
titleText.setText("Sum is " + sum);
} else if (event.getActionCommand().equals("Sum Even")) {
int sum = 0;
for (int i = 0; i <= counter; i++) {
if (numbers[i] % 2 == 0) {
sum += numbers[i];
}
}
titleText.setText("Sum of even values is: " + sum);
} else if (event.getActionCommand().equals("Sum Odd")) {
int sum = 0;
for (int i = 0; i <= counter; i++) {
if (numbers[i] % 2 != 0) {
sum += numbers[i];
}
}
titleText.setText("Sum of odd values is: " + sum);
}
}
}


Below is the modified actionPerformed portion of the code. Removing the last array value now works. However, if the array is full, and the user attempts to remove an element other than the last one, an error is thrown. I am still unsure how to fix this error.

public void actionPerformed(ActionEvent event) {
if (event.getActionCommand().equals("Add")) {
if (counter == 10) {
titleText.setText("Error: too many values");
} else {
numbers[counter] = Integer.parseInt(inputField.getText());
textArea.setText(Arrays.toString(numbers));
counter++;
}
System.out.println("Counter: " + counter);
} else if (event.getActionCommand().equals("Remove")) {
if (Integer.parseInt(inputField.getText()) == numbers[9]) {
numbers[9] = 0;
counter--;
textArea.setText(Arrays.toString(numbers));
} else {
for (int i = 0; i < counter; i++) {
if (Integer.parseInt(inputField.getText()) == numbers[i]) {
for (int x = i; x <= counter - 1; x++) {
numbers[x] = numbers[x + 1];
}
textArea.setText(Arrays.toString(numbers));
counter--;
}
}
}
System.out.println("Counter: " + counter);
} else if (event.getActionCommand().equals("Sum All")) {
int sum = 0;
for (int i = 0; i <= counter; i++) {
sum += numbers[i];
}
titleText.setText("Sum is " + sum);
} else if (event.getActionCommand().equals("Sum Even")) {
int sum = 0;
for (int i = 0; i <= counter; i++) {
if (numbers[i] % 2 == 0) {
sum += numbers[i];
}
}
titleText.setText("Sum of even values is: " + sum);
} else if (event.getActionCommand().equals("Sum Odd")) {
int sum = 0;
for (int i = 0; i <= counter; i++) {
if (numbers[i] % 2 != 0) {
sum += numbers[i];
}
}
titleText.setText("Sum of odd values is: " + sum);
}
}
}

Answer

The below code should remove the integer value correctly if exists. However, it doesn't handle the scenario where multiple values of same integer in the array exists (i.e. array has 1,1,1,1,1,1,1,0,0,0 and try to remove 1) . It doesn't remove all 1s and show all 0s in the text box.

I am not sure whether the requirement is to have unique values in the array. If that is the case, the add function should be changed to handle the scenario.

else if (event.getActionCommand().equals("Remove")) {
            boolean removed = false;
            titleText.setText("Integer Sums");
            for (int i = 0; i < counter; i++) {
                if (Integer.parseInt(inputField.getText()) == numbers[i]) {
                    for (int x = i; x < counter; x++) {
                        if (x == 9) {
                            numbers[x] = 0;
                        } else {
                            numbers[x] = numbers[x + 1];
                            numbers[x + 1] =0;
                        }
                    }
                    textArea.setText(Arrays.toString(numbers));
                    counter--;
                    removed = true;
                }               
            }
            if (!removed) {
                titleText.setText("Error: value doesn't exist");
            } 
            System.out.println("Counter: " + counter);
        } 
Comments