MIT-Curricular/OOP/Java/Lab/Week13/GCD.java

66 lines
1.9 KiB
Java
Raw Permalink Normal View History

2024-10-26 02:15:11 +05:30
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class GCDCalculator extends Application {
@Override
public void start(Stage primaryStage) {
TextField num1Field = new TextField();
num1Field.setPromptText("Enter first number");
TextField num2Field = new TextField();
num2Field.setPromptText("Enter second number");
Label resultLabel = new Label();
Button calculateButton = new Button("Calculate GCD");
calculateButton.setOnAction(e -> {
try {
int num1 = Integer.parseInt(num1Field.getText());
int num2 = Integer.parseInt(num2Field.getText());
if (num1 <= 0 || num2 <= 0) {
resultLabel.setText("Please enter positive integers only");
return;
}
int gcd = calculateGCD(num1, num2);
resultLabel.setText(
String.format("GCD of %d and %d is: %d", num1, num2, gcd)
);
} catch (NumberFormatException ex) {
resultLabel.setText("Please enter valid integers");
}
});
VBox root = new VBox(10);
root.setAlignment(Pos.CENTER);
root
.getChildren()
.addAll(num1Field, num2Field, calculateButton, resultLabel);
Scene scene = new Scene(root, 300, 200);
primaryStage.setTitle("GCD Calculator");
primaryStage.setScene(scene);
primaryStage.show();
}
private int calculateGCD(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
public static void main(String[] args) {
launch(args);
}
}