开发者

Help me to remove the error in my program? [closed]

开发者 https://www.devze.com 2023-02-20 08:08 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class math
{
    JFrame jf;
    JTextField jt;
    JButton jb;
    JButton jb1;
    math()
    {
        jf=new J开发者_如何学编程Frame("frame");
        jf.setSize(200,200);
        jf.setVisible(true);
        jt=new JTextField(50);
        jf.setLayout(new FlowLayout());
        JButton jb=new JButton("30");
        JButton jb1=new JButton("sin");
        jb.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent ae)
            {
                jt.setText("30");
            }
        });
        jb1.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent ae)
            {
                String s=jt.getText();
                double x=Double.parseDouble(s);
                double s1=Math.sin(x);
                jt.setText(s1);
            }
        });
        JButton jb2=new JButton("cos");
        jf.add(jt);
        jf.add(jb);
        jf.add(jb1);
        jf.add(jb2);
    }
    public static void main(String args[])
    {
        new math();
    }
}
//its giving error that double can't be applied to jt.setText


The setText method takes a String, not a double.

You can get a string out of your double by calling Double.toString(someDouble).


javax.swing.text.JTextField.setText(java.lang.String) accepts a String. You can get a String representation of s1 by writing this:

jt.setText(Double.toString(s1));

Now, arguably

jt.setText(String.valueOf(s1));

or

jt.setText(s1 + "");

are better choices because neither will require a change if you refactor s1 to be of some other type.

Personally, I've always found the third choice, string concatenation with the empty string, to be a bit of an inelegant hack.


The error is pretty self-explanatory, I think:

double s1=Math.sin(x);
jt.setText(s1);

The "setText()" method doesn't want a double for an argument, as you're giving it here; it wants a String. So convert your double to a String, and it will work:

double s1=Math.sin(x);
jt.setText(String.valueOf(s1));


The setText method of the TextComponent class expects its argument to be of type String so the double you are trying to pass to it needs to be converted to a String.

Change

jt.setText(s1);

to

jt.setText(Double.toString(s1));
0

精彩评论

暂无评论...
验证码 换一张
取 消