You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
BHD/test.java

104 lines
3.4 KiB

package java6310.lesson01;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class test extends Application {
private TextField inputField;
private ComboBox<String> fromBaseComboBox;
private ComboBox<String> toBaseComboBox;
private TextField outputField;
private Button convertButton;
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("进制转换工具");
Label inputLabel = new Label("输入数值:");
inputField = new TextField();
Label fromBaseLabel = new Label("原进制:");
fromBaseComboBox = new ComboBox<>(FXCollections.observableArrayList("2", "8", "10", "16"));
fromBaseComboBox.getSelectionModel().selectFirst();
Label toBaseLabel = new Label("目标进制:");
toBaseComboBox = new ComboBox<>(FXCollections.observableArrayList("2", "8", "10", "16"));
toBaseComboBox.getSelectionModel().selectFirst();
convertButton = new Button("转换");
convertButton.setOnAction(event -> {
convert();
});
Label outputLabel = new Label("转换结果:");
outputField = new TextField();
outputField.setEditable(false);
VBox layout = new VBox(10);
layout.setPadding(new Insets(10));
layout.getChildren().addAll(inputLabel, inputField, fromBaseLabel, fromBaseComboBox, toBaseLabel, toBaseComboBox, convertButton, outputLabel, outputField);
Scene scene = new Scene(layout, 300, 250);
primaryStage.setScene(scene);
primaryStage.show();
}
private void convert() {
String inputValue = inputField.getText();
int fromBase = Integer.parseInt(fromBaseComboBox.getValue());
int toBase = Integer.parseInt(toBaseComboBox.getValue());
int decimalValue = convertToDecimal(inputValue, fromBase);
String result = convertFromDecimal(decimalValue, toBase);
outputField.setText(result);
}
private int convertToDecimal(String value, int base) {
int decimalValue = 0;
int power = 0;
for (int i = value.length() - 1; i >= 0; i--) {
char digit = value.charAt(i);
int digitValue;
if (digit >= '0' && digit <= '9') {
digitValue = digit - '0';
} else if (digit >= 'A' && digit <= 'F') {
digitValue = digit - 'A' + 10;
} else {
return 0;
}
decimalValue += digitValue * Math.pow(base, power);
power++;
}
return decimalValue;
}
private String convertFromDecimal(int decimalValue, int base) {
if (decimalValue == 0) {
return "0";
}
StringBuilder result = new StringBuilder();
while (decimalValue > 0) {
int remainder = decimalValue % base;
char digit;
if (remainder < 10) {
digit = (char) ('0' + remainder);
} else {
digit = (char) ('A' + remainder - 10);
}
result.insert(0, digit);
decimalValue /= base;
}
return result.toString();
}
public static void main(String[] args) {
launch(args);
}
}