gpt4 book ai didi

java - 输入更新后不存储 JTextArea 中的预期字符串

转载 作者:太空宇宙 更新时间:2023-11-04 10:01:40 25 4
gpt4 key购买 nike

我在计算器中有一个具有工作按钮的内部类。我有一个 JTextArea,其中按下按钮将注册数字 1-9,然后在选择操作后打印新行。选择操作后,我有一个 boolean 值,它将在再次打印之前检查是否计算结果。我尝试分割每个数字并使用以下方法存储它:

String s = textArea.getText();
String[] parts = s.split("\n|\\=|\\-|\\/|\\*|\\+");

虽然我期待类似的事情

100+

100=

200+

我反而遇到了:

100+

100=

java.lang.NumberFormatException:空字符串

为了进行这些计算,我使用了以下代码片段:

if(s.length() > 0){
if(calc == true){
textArea.setText(textArea.getText() + "=" + "\n");
d2 = Double.parseDouble(parts[counter]);
result = d1 + d2;
textArea.setText(textArea.getText() + result + buttonText + "\n");
d1 = d2;
}
if(Character.isDigit(s.charAt(s.length()-1)) && calc == false){
textArea.setText(textArea.getText() + buttonText + "\n");
d1 = Double.parseDouble(parts[counter]);
counter++;
calc = true;
}
}

有没有办法存储每次输入后要使用的数字而不会遇到此错误?

编辑:该行发生错误

Double.parseDouble(parts[counter]);

删除后不会出现错误,但仍可以正常打印。我通过使用 Double.parseDouble(parts[0]); 测试注意到了什么它可以工作并返回从按钮输入的第一个字符串,但似乎在此之后没有更多的值存储到

String[] parts = s.split("\n|\\=|\\-|\\/|\\*|\\+");

数组,尽管附加输入满足分隔符要求,但它似乎停在那里。我想知道这是否是由于 split 方法未向数组添加额外输入的问题造成的。

根据要求,我还在这里发布了相关的完整代码

class operands implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
Object obj = event.getSource();
JButton but = null;
String buttonText = "";
//casts button with object
if(obj instanceof JButton)
{
but = (JButton) obj;
}
//sets string of text to button text
if(but != null)
{
buttonText = but.getText();
}
String s = textArea.getText();
//store numbers after each operand
String[] parts = s.split("\n|\\=|\\-|\\/|\\*|\\+");
if(s.length() > 0)
{
if(calc)
{
//performs calculation and returns result
textArea.setText(textArea.getText() + "=" + "\n");
d2 = Double.parseDouble(parts[counter]);
result = d1 + d2;
textArea.setText(textArea.getText() + result + buttonText + "\n");
d1 = d2;
}
if(Character.isDigit(s.charAt(s.length()-1)) && !calc)
{
//updates function to perform calculation on next operand
textArea.setText(textArea.getText() + buttonText + "\n");
d1 = Double.parseDouble(parts[counter]);
counter++;
calc = true;
}
}
}

最佳答案

感谢所有试图提供帮助的人。我发现了这个问题。

对于字符串 .split() 函数,我将“\n”作为分隔符之一。这样做似乎在将数字存储到字符串中存在问题,因此会将空结果存储到数组中。从分隔符中删除换行符似乎已经解决了问题。

关于java - 输入更新后不存储 JTextArea 中的预期字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53387966/

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