gpt4 book ai didi

java - 代码可以编译但不能运行

转载 作者:行者123 更新时间:2023-12-01 12:58:16 25 4
gpt4 key购买 nike

这是一个简单的计算器;我的代码可以编译但无法正常工作。我的意思是它不执行或运行:

   import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Calc implements ActionListener{

JFrame frame;
JButton plus,mul;
JTextField op1,op2,ans;
JLabel firstOperand, secondOperand,answer;
// setting layout

public void initGUI(){

frame = new JFrame();////set top level container
Container con = frame.getContentPane();
con.setLayout(new FlowLayout());

firstOperand = new JLabel("First Operand");g their constructor
secondOperand = new JLabel("Second Operand");
answer = new JLabel("Answer");

plus = new JButton("+");
plus.setPreferredSize(new Dimension(70,25));
mul = new JButton("*");
mul.setPreferredSize(new Dimension(70,25));

con.add(firstOperand);
con.add(op1);r

con.add(secondOperand);
con.add(op2);

con.add(plus);
con.add(mul);

con.add(answer);
con.add(ans);


plus.addActionListener(this);
mul.addActionListener(this);

// set size of frame and make it visible
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200,220);
frame.setVisible(true);

}//end of initilization GUI

//constructor
public Calc(){

initGUI();// jab obj create ho ga to call ho ga


}
// actionperformed() method of ActionListener

public void actionPerformed(ActionEvent event){

String oper, result;
int num1,num2,res;
//System.out.println(event.getSource);
if(event.getSource() == plus){
oper = op1.getText();
oper = op2.getText();
num2 = Integer.parseInt(oper);
res = num1 + num2;//add operands
result = res+"";
ans.setText(result);
}
else if (event.getSource() == mul){
oper = op1.getText();
num1 = Integer.parseInt(oper);
oper = op2.getText();
num2 = Integer.parseInt(oper);
res = num1 * num2;//add operands
result = res+"";
ans.setText(result);

}


}// end of actionPerformed method

public static void main(String args[]){

Calc cl = new Calc();// making object for Cals class

}
}

最佳答案

您的 JTextField 未初始化。初始化它们

op1 = new JTextField();
....

关于java - 代码可以编译但不能运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23720870/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com