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.

56 lines
1.8 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package FirstDemo;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
public class demoController {
@FXML
private TextField initialBaseField;
@FXML
private TextField numberToConvertField;
@FXML
private TextField targetBaseField;
@FXML
private Label resultLabel;
@FXML
private void convert() {
try {
int sourceBase = Integer.parseInt(initialBaseField.getText());
String sourceNumber = numberToConvertField.getText();
int targetBase = Integer.parseInt(targetBaseField.getText());
int decimalValue = toDecimal(sourceNumber, sourceBase);
String targetNumber = fromDecimal(decimalValue, targetBase);
resultLabel.setText("转换成 " + targetBase + " 进制的结果为: " + targetNumber);
} catch (NumberFormatException e) {
resultLabel.setText("输入无效,请确保输入有效的进制和数字。");
} catch (Exception e) {
resultLabel.setText("发生错误:" + e.getMessage());
}
}
// 将输入转换为10进制
public static int toDecimal(String number, int base) {
return Integer.parseInt(number, base);
}
// 将转换后的10进制数转换为目标进制数
public static String fromDecimal(int number, int base) {
StringBuilder sb = new StringBuilder();
while (number > 0) {
int remainder = number % base;
// 对于大于9的数字用字母A-F表示
if (remainder >= 10) {
sb.append((char) ('A' + remainder - 10));
} else {
sb.append(remainder);
}
number /= base;
}
return sb.reverse().toString(); // 反转字符串以得到正确的顺序
}
}