700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > java求阶乘不内存溢出_java - Java阶乘GUI - 堆栈内存溢出

java求阶乘不内存溢出_java - Java阶乘GUI - 堆栈内存溢出

时间:2020-12-18 13:32:05

相关推荐

java求阶乘不内存溢出_java - Java阶乘GUI - 堆栈内存溢出

目的是创建一个利用GUI计算阶乘的程序。 我需要创建一个jPanel或jFrame来显示程序的结果。 然后,我需要从JTextField获取文本并将其解析为Integer,以便可以将其传递给构造函数。 第三,需要使用一个称为factorial的int类型的实例变量来创建一个对象类。 该对象类需要一个名为Factorial的单个参数构造函数,该构造函数接受一个int并将其值分配给实例变量。 然后,它应该具有一种使用for循环(返回类型为int)来计算阶乘的方法。 最后,它应该在调用计算阶乘的方法后显示对象的值。 到目前为止,这是我的工作。

import javax.swing.JFrame;

public class factorialCalc

{

public static void main (String[] args)

{

JFrame frame=new JFrame ("Factorial Calculator");

frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

Factorial panel=new Factorial();

frame.getContentPane().add(panel);

frame.pack();

frame.setVisible(true);

}

}

我的下一个文件是Object类:

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class Factorial extends JPanel

{

private int factorial;

private JLabel inputLabel,resultLabel;

private JTextField factorialText;

private JButton factButton;

//Constructor: sets up main GUI components

public void FactorialPanel(int factorial)

{

this.factorial=factorial;

inputLabel= new JLabel ("Please enter an integer:");

factButton = new JButton("Compute");

TempListener listener=new TempListener();

factButton.addActionListener(listener);

factorialText = new JTextField();

factorialText.addActionListener (new TempListener());

add(inputLabel);

add(factorialText);

add(resultLabel);

}

//represents a listener for the button

private class TempListener implements ActionListener

{

//performs factorial operation when the 'Compute' button is pressed

public int computeFactorial(ActionEvent event)

{

int text=Integer.parseInt(factorial);

int f =1;

for(int i=text;i>=1;i--)

{

f = f*i;

}

resultLabel.setText(Integer.toString(f));

}

}

}

这些是我尝试编译时遇到的以下错误:

.\Factorial.java:31: error: Factorial.TempListener is not abstract and does not override abstract method actionPerformed(ActionEvent) in ActionListener

private class TempListener implements ActionListener

^

.\Factorial.java:37: error: incompatible types: int cannot be converted to String

int text=Integer.parseInt(factorial);

^

Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output

2 errors

为什么不让我将String阶乘解析为in和integer?

另外,如何以及在何处调用computeFactorial方法以显示对象的值?

谢谢! 任何帮助表示赞赏!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。