我必须在java中调用gcd方法编写一个applet,并在showStatus中显示输出。 这是我到目前为止所做的,但是当我给出这两个数字时,返回值只是第二个数字。任何人都告诉我这有什么问题?
任何帮助都会非常感激。
package gcd;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Gcd extends JApplet implements ActionListener {
JLabel promptLabel1,promptLable2;
JTextField inputField1,inputField2;
public void init(){
Container container = getContentPane();
container.setLayout( new FlowLayout() );
promptLabel1 = new JLabel( "Enter first number: " );
promptLable2 = new JLabel( "Enter second number: " );
inputField1 = new JTextField( 10 );
inputField1.addActionListener( this );
inputField2 = new JTextField( 10 );
inputField2.addActionListener( this );
container.add( promptLabel1 );
container.add( inputField1 );
container.add( promptLable2 );
container.add( inputField2 );
}
@Override
public void actionPerformed(ActionEvent actionEvent) {
int num1 = Integer.parseInt( actionEvent.getActionCommand());
int num2 = Integer.parseInt( actionEvent.getActionCommand());
showStatus( "Great Common Divisor is " + gcd( num1,num2 ) );
}
public int gcd (int num1,int num2){
while(num1!=0 && num2!=0){
int temp = num2;
num2 = num1%num2;
num1 = temp;
}
return num1+num2;
}
}
答案 0 :(得分:2)
你应该用这个:
int num1 = Integer.parseInt(inputField1.getText());
int num2 = Integer.parseInt(inputField2.getText());
从框中获取文本输入。