我需要帮助在我的程序中找到错误。 任务是: 递归乘法。
编写一个使用递归函数的GUI程序。用户将在文本字段中输入一个数字,当单击一个按钮时,该按钮将调用一个名为递归的函数。
此函数接受参数x和y中的两个参数。该函数应返回x乘以y的值。请记住,乘法可以重复加法执行如下:7 * 4 = 4 + 4 + 4 + 4 + 4 + 4 + 4或7 * 4 = 7 + 7 + 7 + 7
测试您的程序是否为负数。
这是我的计划:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Recursion extends JFrame implements ActionListener {
private JLabel xLabel; // To reference a label
private JLabel yLabel; // To reference a label
private JTextField xTextField; // To reference a text field
private JTextField yTextField; // To reference a text field
private JTextField resultField; // To reference a text field
private JButton calcButton; // To reference a calculate button
private int total = 0;
public Recursion() {
// Set the title bar text.
setTitle("Multiplication");
// Specify an action for the close button.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Add a FlowLayout manager to the content pane.
setLayout(new FlowLayout());
// Set the size of the window.
setSize(450, 120);
xLabel = new JLabel("Enter x");
add(xLabel);
xTextField = new JTextField("0", 8);
add(xTextField);
yLabel = new JLabel("Enter y");
add(yLabel);
yTextField = new JTextField("0", 8);
add(yTextField);
// Create a read-only text field for the result.
resultField = new JTextField("0", 8);
resultField.setEditable(false);
add(resultField);
// Create a button with the caption "Calculate".
calcButton = new JButton("Calculate");
add(calcButton);
calcButton.addActionListener(this);
// Display the window.
setVisible(true);
}
public void actionPerformed(ActionEvent evt)
{
int x = Integer.parseInt(xLabel.getText());
int y = Integer.parseInt(yLabel.getText());
total = Multiply(x,y);
resultField.setText(" " + total);
}
public int Multiply(int x,int y){
if(y==1)
return x;
else
{
return x + Multiply(x, y-1);
}
}
public static void main(String[] args) {
Recursion app = new Recursion();
}
}
编译器显示此错误:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "Enter x"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)....................
...............................
我错过了什么?
提前致谢。