-3
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JTextField;
public class autos extends JPanel implements ActionListener {
    private static final long serialVersionUID = 1L;
    String get;
    int logic = 0, b;
    JFrame frame = new JFrame("Tic Tac Toe");
    JTextField text = new JTextField(1);
    public autos() {
        JButton button = new JButton("LOAD");
        add(button);
        add(text);
        setLayout(null);
        button.setBounds(70, 70, 80, 40);
        text.setBounds(140, 140, 20, 20);
        text.addActionListener(this);
        if (duvoi.equals("x")) logic = 1;
        else if (get.equals("0")) logic = 2;
        else logic = 0;
    }
    public void paint(Graphics g) {
        super.paint(g);
        if (logic == 1) 
        g.drawString("You entered x", 200, 100);
        else if (logic == 2) 
        g.drawString("You entered", 200, 100);
        else b = 23;
        repaint();
    }
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.getContentPane().add(new autos());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);
        frame.setVisible(true);
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        get = text.getText();
    }
}

When I try to run the code,I get these errors:

Exception in thread "main" java.lang.NullPointerException at autos.(autos.java:27) at autos.main(autos.java:48)

I am using eclipse.Why do these errors appear and what can I do to get rid of them?

singhakash
  • 7,891
  • 6
  • 31
  • 65
Daniel Tork
  • 113
  • 10
  • What have you tried? What's on line 48? Have you looked up what java.lang.NullPointerException means? Are all your variables initialized? – Duston Oct 08 '15 at 17:12

1 Answers1

0

You never initialize get after you declare it.

String get;

and then you call

else if(get.equals("0"))

at that point, get is null. And so, you've said else if (null.equals("0")) which causes a NullPointerException. One possible solution is Yoda conditions. Like,

else if("0".equals(get)) // <-- won't throw NPE.
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249