parent
4318b67bcd
commit
8f220df62d
@ -0,0 +1,68 @@
|
||||
import javax.swing.*;
|
||||
import java.awt.*;
|
||||
import java.awt.event.ActionEvent;
|
||||
import java.awt.event.ActionListener;
|
||||
|
||||
public class BaseConversion2 {
|
||||
public static int convertToDecimal(String number, int base) {
|
||||
int decimalValue = 0;
|
||||
int power = 0;
|
||||
|
||||
for (int i = number.length() - 1; i >= 0; i--) {
|
||||
char digit = number.charAt(i);
|
||||
int digitValue;
|
||||
|
||||
if (Character.isDigit(digit)) {
|
||||
digitValue = digit - '0';
|
||||
} else {
|
||||
digitValue = Character.toUpperCase(digit) - 'A' + 10; // A-F
|
||||
}
|
||||
|
||||
decimalValue += digitValue * Math.pow(base, power);
|
||||
power++;
|
||||
}
|
||||
|
||||
return decimalValue;
|
||||
}
|
||||
|
||||
public static String convertFromDecimal(int number, int base) {
|
||||
StringBuilder result = new StringBuilder();
|
||||
|
||||
if (number == 0) {
|
||||
return "0";
|
||||
}
|
||||
|
||||
while (number > 0) {
|
||||
int remainder = number % base;
|
||||
if (remainder < 10) {
|
||||
result.append((char) ('0' + remainder));
|
||||
} else {
|
||||
result.append((char) ('A' + remainder - 10));
|
||||
}
|
||||
number /= base;
|
||||
}
|
||||
|
||||
return result.reverse().toString();
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
JFrame frame = new JFrame("进制转换器");
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
frame.setSize(400, 300);
|
||||
frame.setLayout(new GridLayout(5, 2));
|
||||
|
||||
JLabel sourceBaseLabel = new JLabel("源进制 (2-16):");
|
||||
JTextField sourceBaseField = new JTextField();
|
||||
|
||||
JLabel targetBaseLabel = new JLabel("目标进制 (2-16):");
|
||||
JTextField targetBaseField = new JTextField();
|
||||
|
||||
JLabel numberLabel = new JLabel("要转换的数字:");
|
||||
JTextField numberField = new JTextField();
|
||||
|
||||
JButton convertButton = new JButton("转换");
|
||||
JLabel resultLabel = new JLabel("转换结果:");
|
||||
|
||||
convertButton.addActionListener(new ActionListener() {
|
||||
@Override
|
||||
public void actionPerf
|
Loading…
Reference in new issue