gpt4 book ai didi

java - 如何从文本字段添加输入

转载 作者:行者123 更新时间:2023-12-02 07:00:40 25 4
gpt4 key购买 nike

下面是我的代码,我将突出显示引发错误的原因,我完全不知道如何解决此问题...

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

抛出错误的代码用 ** 标记给出的错误是:二元运算符“+”的操作数类型错误

请帮忙!

谢谢

最佳答案

您不能将 TextFields 添加在一起,并且 Java 不支持重载。要获取值,您必须首先对每个 TextField 调用 getText(),然后将其传递给 Double.parseDouble 将其转换为数字Java 可以添加。

你应该有这样的东西:

double gpa = (Double.parseDouble(Math.getText()) +
...
Double.parseDouble(Elective2.getText())
) / 6;

如果任何 TextField 包含无法转换为数字的文本,则需要捕获 NumberFormatException

然后,您需要将 GPA 转换为您称为 messageTextArea 的文本。

message.setText(String.valueOf(gpa));

关于java - 如何从文本字段添加输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16703403/

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