下面是我的代码,我将重点介绍错误是什么,我完全不知道如何解决这个错误...
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.awt.event.ActionListener.*;
import java.awt.event.TextListener.*;
public abstract class GradeAverage extends Applet
implements ActionListener, TextListener{
Button Ok=new Button("Ok");
Button Cancel=new Button("cancel");
TextField Math=new TextField("Math Grade",2);
TextField Science=new TextField("Scien Grade",2);
TextField SocialStudies=new TextField("Social Studies Grade",2);
TextField English=new TextField("English Grade",2);
TextField Elective=new TextField("Elective Grade",2);
TextField Elective2=new TextField("2nd Elective Grade",2);
TextArea message=new TextArea();
public void init(){
GridBagLayout gbl=new GridBagLayout();
setLayout(gbl);
GridBagConstraints c=new GridBagConstraints();
c.anchor=GridBagConstraints.WEST;
c.weightx=2.0;
c.weighty=2.0;
c.fill=GridBagConstraints.HORIZONTAL;
c.insets=new Insets(10,10,10,10);
gbl.setConstraints(Math,c); add(Math);
c.fill=GridBagConstraints.NONE;
gbl.setConstraints(Science,c); add(Science);
c.fill=GridBagConstraints.HORIZONTAL;
gbl.setConstraints(SocialStudies,c); add(SocialStudies);
c.gridy=1;
gbl.setConstraints(English,c); add(English);
c.gridy=2;
gbl.setConstraints(Elective,c); add(Elective);
c.fill=GridBagConstraints.NONE;
gbl.setConstraints(Elective2,c); add(Elective2);
c.gridy=3;
c.anchor=GridBagConstraints.CENTER;
gbl.setConstraints(Ok,c); add(Ok);
gbl.setConstraints(Cancel,c); add(Cancel);
c.gridy=4;
c.gridwidth=3;
c.fill=GridBagConstraints.BOTH;
gbl.setConstraints(message,c); add(message);
Math.addTextListener(this);
Science.addTextListener(this);
SocialStudies.addTextListener(this);
English.addTextListener(this);
Elective.addTextListener(this);
Elective2.addTextListener(this);
Ok.addActionListener(this);
Cancel.addActionListener(this);
}
public void actionPerformed(ActionEvent event){
Object Source=event.getSource();
if(Source==Ok){
Math.getText();
Science.getText();
SocialStudies.getText();
English.getText();
Elective.getText();
Elective2.getText();
do{
**message=(Math+Science+SocialStudies+English+Elective+Elective2)/6;**
system.println("Your grade average is"+message);
}while (message<0);
if(Source==Cancel){
system.ext(0);
}
}}}
抛出错误的代码标有** 给出的错误是:二元运算符'+'
的坏操作数类型请帮忙!
由于
答案 0 :(得分:2)
您不能将TextFields
添加到一起,Java不支持重载。要获得该值,您必须先在getText()
上调用TextField
,然后将其传递给Double.parseDouble
,将其转换为Java可以添加的数字。
你应该有这样的东西:
double gpa = (Double.parseDouble(Math.getText()) +
...
Double.parseDouble(Elective2.getText())
) / 6;
如果任何NumberFormatException
包含无法转换为数字的文字,则需要抓取TextField
。
然后,您需要将GPA转换为TextArea
您调用message
的文本。
message.setText(String.valueOf(gpa));
答案 1 :(得分:0)
看起来您正在尝试将字符串变量添加到一起 - 尝试首先将它们转换为整数值。
之类的东西 message=(Integer.parseInt(Math)+Integer.parseInt(Science)+Integer.parseInt(English)...
以下是此主题的另一个主题的链接:How to convert a String to an int in Java?
希望这能帮到你!