2

好的,我正在用 Java 编写一个计算器,并将 a 输入String到我的加法方法中。我JButtons用来将文本写入JTextField.

当用户单击等号按钮时,我找到了他们想要执行的相对操作(如果他们单击运算符按钮,我将 int 设置为特定数字(因此加法为 1))。我首先将 转换Stringchar数组,然后检查字符是数字还是运算符。

我计划为我要使计算器能够进行的所有计算(加法,减法等)编写几种方法。然后,我使用该.append方法将不是运算符的字符写入StringBuffers,然后将其转换为字符串,然后再转换为双精度值。然后我执行计算,并返回结果。

当我尝试使用计算器时,Eclipsejava.lang.NumberFormatException会在我尝试将保存 的字符串StringBuffer转换为double. 异常是由空的String.

任何人都可以解释为什么会发生这种情况并提供解决方案吗?

以下是相关代码:

import java.awt.event.*;
import javax.swing.*;
import java.awt.GridLayout;


public class Calculator2012 extends JFrame implements ActionListener{

    public static double calculateAdd(String inputString)//this is my addition method
    {
        int s = 0;
        boolean g = true;
        StringBuffer num1 = new StringBuffer();
        StringBuffer num2 = new StringBuffer();
        char[] b = inputString.toCharArray();
        int i = 0;
        if(g==true)
        {
            for(int v = 0; v<b.length; v++)
            {
                if(b[i]!='+')
                {
                    num1.append(b[i]);
                }
                else 
                {
                    g = false;
                    s = ++i;
                    break;
                }
                i++;
            }
        }
        else
        {
            for(int a = 0; a<(b.length-s); a++)
            {
                num2.append(b[s]);
                s++;
            }
        }
        String c1 = num1.toString();
        String c2 = num2.toString();
        double x = Double.parseDouble(c1);
        double y = Double.parseDouble(c2);//this is the error producing line
        double z = x+y;
        return z;
    }

这是我的方法调用:

public void actionPerformed(ActionEvent e)
{
    //omitted irrelevant code

    if(e.getSource()==equals)
    {
        s1 = tf1.getText();
        s2 = " = ";
        s3 = s1+s2;
        tf1.setText(s3);
        if(p==1)//p is my int that detects which operator  to use
        {
            s1 = tf1.getText();
            s2 = Double.toString(calculateAdd(s1));//I call the method here
            s3 = s1+s2;
            tf1.setText(s3);
4

1 回答 1

3

由于gis true,这部分永远不会执行:

    else
    {
        for(int a = 0; a<(b.length-s); a++)
        {
            num2.append(b[s]);
            s++;
        }
    }

因此num2永远不会填充,并且您会遇到尝试解析空字符串的异常。

于 2012-07-30T20:29:42.583 回答