JAVA The following program contains exactly three 3 errors P

JAVA

The following program contains exactly three (3) errors. Please identify them.

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.*;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;

class Cell extends JButton {

private static final int NUM_COLOURS = 3;

private ImageIcon[] icons;
private int type;

public Cell() {
ImageIcon[] icons;

icons = new ImageIcon[NUM_COLOURS];
for (int i=0; i<NUM_COLOURS; i++) {
icons[i] = new ImageIcon(\"data/ball-\" + Integer.toString(type) + \".png\");
}

this.type = 0;
setBackground(Color.WHITE);
setIcon();
setBorderPainted(false);
}

private void setIcon() {
setIcon(icons[type]);
}

public void update() {
type = type + 1;
setIcon();
}
  
}

public class App extends JFrame implements ActionListener {

private Cell myCell;
  
public App() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myCell = new Cell();
myCell.addActionListener(this);
add(myCell);
pack();
setVisible(true);
}

public void actionPerformed(ActionEvent e) {
myCell.update();
}
  
public static void main(String[] args) {
new App();
}
  
}

Solution

Basically, all the errors are displayed because of 1 thing : NullPointerException.

This is happening because there are icons [ ] arrays that are defined 2 times. In the public Cell() method, there is a local initialization of ImageIcon icons[ ] that is hiding the class element icons[ ] .

setIcon() method operates on class variable icons[ ] which is never initialized as in Cell() constructor, local icons[ ] array is defined and used but never assigned to class element.

So, you can solve this in 2 ways:

1. remove icons[ ] in Cell constructor i.e. 1st line of that constructor. That means the constructor directly operates on class variable.

2. In the Cell() constructor, add 1 line: this.icons = icons;

Here, this.icons represent class variable and the right hand side icons is local variable defined in 1st line of the same method.

Use either of these, try to use 1st one. This solves the problem and the code is running.

Do comment if there is any query. Thank you. :)

JAVA The following program contains exactly three (3) errors. Please identify them. import java.awt.Color; import java.awt.GridLayout; import java.awt.event.*;
JAVA The following program contains exactly three (3) errors. Please identify them. import java.awt.Color; import java.awt.GridLayout; import java.awt.event.*;

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site