gpt4 book ai didi

java - java制作计算器时出现NumberFormatException等问题

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

所以我正在制作一个 Java 计算器,并在单击功能按钮时遇到一些错误(尽管它编译得很好)。我的 CMD 中第一行的错误是 NumberFormat 异常。经过一番搜索后,我发现在我的代码中的某个地方,我试图从空字符串中获取 double 值(基本上我想做的是从标签文本中解析 double 值)。我猜是这部分:

// if statement that puts the labels text into the first or second number
if(firstNumber)
{
number1 = Double.parseDouble(label.getText().trim());
} else {
number2 = Double.parseDouble(label.getText().trim());
}

基本上问题是当我按下/* + 或 - 按钮时,我得到一个 NumberFormatExeption: For input string "/"等。我不太清楚如何修复这个错误(我仍然(在某种程度上)是Java的初学者)。在错误行的更深处(有很多)是很多我不理解的错误,例如 EventDispatchThread、EventQueue 和许多其他错误。我也找不到关于我的经验水平的解释,所以我在这里寻求帮助。

数字按钮都工作正常。

运行时:[ http://gyazo.com/71cb4dde449ccf7ece44017388a71a0f]

输入数字:[ http://gyazo.com/5c7ab6c54ac6da180845c66866d66f8f]

所有其他按钮都会在我的 CMD 中出现错误。

这是我的代码(某些部分的间距可能会困惑):

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
// import for Nimbus look
import javax.swing.UIManager.*;

public class Calculator extends JFrame implements ActionListener
{
private JPanel bottom = new JPanel(); private JPanel top = new JPanel();
private JLabel label = new JLabel(" ");
private JButton[] buttons = new JButton[16];
// booleans for calculator functions
boolean add = false, substract = false, devide = false, multiply = false, firstNumber = true;
// numbers that will be calculated
double number1, number2;

public Calculator()
{
setLayout(new BoxLayout(getContentPane(), BoxLayout.PAGE_AXIS));

// bottom panel
bottom.setPreferredSize(new Dimension(100,100));
bottom.setLayout(new BorderLayout());

//add bottom panel to frame
add(bottom);

// top panel
top.setPreferredSize(new Dimension(300,400));
top.setLayout(new GridLayout(4,4,3,3));
top.setBackground(Color.BLACK);
//dont add top panel to frame: you want top to be on bottom

// add top panel to bottom panel
bottom.add(top);

// label
label.setFont(new Font("Courier", Font.PLAIN, 20));
label.setBackground(Color.BLACK);
label.setForeground(Color.WHITE);
label.setHorizontalAlignment(SwingConstants.RIGHT); // text is right-aligned
label.setOpaque(true);

// add the label to the bottom panel
bottom.add(label, BorderLayout.NORTH);

// creating buttons
for(int i = 0; i < buttons.length; i++)
{
buttons[i] = new JButton("789/456*123+c0=-".substring(i, i+1));
buttons[i].addActionListener(this);
// add them to the top panel
top.add(buttons[i]);
}

// Nimbus look
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
// If Nimbus is not available, you can set the GUI to another look and feel.
//set to default somehow o.o
}

// frame setters
setTitle("Calculator");
setSize(400,400);
setVisible(true);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}

public void Clear()
{
label.setText(" ");
}

@Override
public void actionPerformed(ActionEvent e)
{
//if's for all function buttons
if(e.getSource() == buttons[3])
{
// devide
devide = true;

substract = false;
add = false;
multiply = false;

firstNumber = false;
Clear();

label.setText("/");
}

if(e.getSource() == buttons[7])
{
// multiply
multiply = true;

substract = false;
devide = false;
add = false;

firstNumber = false;
Clear();

label.setText("*");
}

if(e.getSource() == buttons[11])
{
// add
add = true;

substract = false;
devide = false;
multiply = false;

firstNumber = false;
Clear();

label.setText("+");
}

if(e.getSource() == buttons[12])
{
// clear
label.setText("0");
number1 = 0.00;
number2 = 0.00;

add = false;
substract = false;
devide = false;
multiply = false;

firstNumber = true;
Clear();
}

if(e.getSource() == buttons[15])
{
// substract
substract = true;

add = false;
devide = false;
multiply = false;

firstNumber = false;
Clear();

label.setText("-");
}

// for loops that add the numbers on the buttons to the label
for(int i = 0; i < 3; i++)
{
if(e.getSource() == buttons[i])
{
if(label.getText() == "0")
{
label.setText("");
label.setText(label.getText() + buttons[i].getText());
} else {
label.setText(label.getText() + buttons[i].getText());
}
}
}

for(int i = 4; i < 7; i++)
{
if(e.getSource() == buttons[i])
{
if(label.getText() == "0")
{
label.setText("");
label.setText(label.getText() + buttons[i].getText());
} else {
label.setText(label.getText() + buttons[i].getText());
}
}
}

for(int i = 8; i < 11; i++)
{
if(e.getSource() == buttons[i])
{
if(label.getText() == "0")
{
label.setText("");
label.setText(label.getText() + buttons[i].getText());
} else {
label.setText(label.getText() + buttons[i].getText());
}
}
}

for(int i = 13; i < 14; i++)
{
if(e.getSource() == buttons[i])
{
if(label.getText() == "0")
{
label.setText("");
label.setText(label.getText() + buttons[i].getText());
} else {
label.setText(label.getText() + buttons[i].getText());
}
}
}

// if statement that puts the labels text into the first or second number
if(firstNumber)
{
number1 = Double.parseDouble(label.getText().trim());
} else {
number2 = Double.parseDouble(label.getText().trim());
}

// calculation
if(e.getSource() == buttons[14])
{
// calculate
if(devide){number1 = ((double)(number1) / (double)(number2)); }
if(multiply){number1 = ((double)(number1) * (double)(number2)); }
if(add){number1 = ((double)(number1) + (double)(number2)); }
if(substract){number1 = ((double)(number1) - (double)(number2)); }
label.setText(Double.toString(number1));
}

}

public static void main(String[] args)
{
new Calculator();
}
}

最后,计算器的计算结果是不正确的。我也无法理解造成这种情况的原因。请记住,我是 Java 初学者,这是我在 stackoverflow 上的第一个问题。预先感谢您帮助我,无论谁愿意:)

更新:我通过按如下方式放置代码来修复错误:

if(e.getSource() == buttons[15])
{
// substract
substract = true;

add = false;
devide = false;
multiply = false;

firstNumber = false;
isNumberKey = false;

if(isNumberKey)
{
if(firstNumber)
{
label.setText(label.getText().replace("/",""));
label.setText(label.getText().replace("*",""));
label.setText(label.getText().replace("+",""));
label.setText(label.getText().replace("-",""));
number1 = Double.parseDouble(label.getText().trim());
} else {
label.setText(label.getText().replace("/",""));
label.setText(label.getText().replace("*",""));
label.setText(label.getText().replace("+",""));
label.setText(label.getText().replace("-",""));
number2 = Double.parseDouble(label.getText().trim());
}
}

Clear();

label.setText("-");
}

我现在需要做的就是修正计算...感谢大家的帮助!

最佳答案

无法完全深入研究您的逻辑,但这里有一些提示:

首先,您不必猜测错误出在哪里。如果出现像这里这样的未捕获异常,产生该异常的线程会将其堆栈跟踪打印到控制台。它看起来像这样:

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "/"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1222)
at java.lang.Double.parseDouble(Double.java:510)
at mypackage.Calculator.actionPerformed(Calculator.java:229)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6297)

从这里您可以看到,异常发生在名为 AWT-EventQueue-0 的线程中,该线程是 swing 的标准事件调度线程(所有 GUI 应用程序都在单线程中处理事件)。在堆栈跟踪中搜索的另一件事是查找代码中的哪一行抛出了它。这是一行:

at mypackage.Calculator.actionPerformed(Calculator.java:229)

在源代码中,它是行:

number2 = Double.parseDouble(label.getText().trim());

,所以你猜对了。您可以做的是在那里添加另一个 boolean 值,仅当点击数字按钮时才会设置该 boolean 值,然后将该部分代码更改为如下所示:

if( isNumber){
if(firstNumber)
{
number1 = Double.parseDouble(label.getText().trim());
} else {
number2 = Double.parseDouble(label.getText().trim());
}
}

除此之外,不要使用多个 boolean 标志进行操作,而是使用 Java 枚举类型

enum Operation {devide, substract, add, multiply};

您的代码将更具可读性并且具有“java”风格。良好的起点,继续吧!

关于java - java制作计算器时出现NumberFormatException等问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27173210/

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