未知的java类错误

时间:2015-10-08 17:09:05

标签: java compiler-errors jframe jpanel

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();
    }
}

当我尝试运行代码时,我收到了以下错误:

  

线程“main”中的异常java.lang.NullPointerException at   autos。(autos.java:27)at autos.main(autos.java:48)

我正在使用eclipse。为什么会出现这些错误,我该怎么做才能摆脱它们?

1 个答案:

答案 0 :(得分:0)

宣布后,您永远不会初始化get

String get;

然后你打电话

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

此时,getnull。所以,您已经说else if (null.equals("0"))会导致NullPointerException。一种可能的解决方案是Yoda conditions。像,

else if("0".equals(get)) // <-- won't throw NPE.