简体   繁体   中英

why doesn't this gcd method work?

I have to write an applet in java calling gcd method and shows the output in showStatus. This is what i have done so far but when i give the two numbers , the return value is only the second number.can anyone tell me what's wrong with this?

any help would be much appreciated.

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;
   }
  }

You should use this:

int num1 = Integer.parseInt(inputField1.getText());
int num2 = Integer.parseInt(inputField2.getText());

Get the text input from the boxes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM