好的,我正在用 Java 编写一个计算器,并将 String
输入添加到我的加法方法中。我使用 JButtons
将文本写入 JTextField
。
当用户单击等于按钮时,我找到他们想要执行的相对操作(如果他们单击运算符按钮,我将 int 设置为特定数字(因此加法为 1))。我首先将 String
转换为 char
数组,然后检查字符是否是数字或运算符。
我计划为计算器的所有计算编写几种方法(加法、减法等)。然后,我使用 .append
方法将不是运算符的字符写入 StringBuffers
中,然后将其转换为字符串,然后再转换为 double 。然后我执行计算并返回结果。
当我尝试使用计算器时,Eclipse 在我尝试将保存 StringBuffer
的字符串转换为 的行上报告
。该异常是由空java.lang.NumberFormatException
>双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);
最佳答案
由于 g
为 true
,因此这部分永远不会执行:
else
{
for(int a = 0; a<(b.length-s); a++)
{
num2.append(b[s]);
s++;
}
}
因此 num2
永远不会被填充,并且您会在尝试解析空字符串时遇到异常。
关于java - Java中的计算方法计算器产生空字符串错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11728983/