import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Scanner; public class Transform2158{ public static String convertBase(String input, int fromBase, int toBase) { try { int number = Integer.parseInt(input, fromBase); return Integer.toString(number, toBase); } catch (NumberFormatException e) { return null; } } public static boolean isValidBase(int base) { return base == 2 || base == 8 || base == 10 || base == 16; } public static void main(String[] args) { if (args.length > 0 && args[0].equals("cli")) { runCLI(); } else { SwingUtilities.invokeLater(() -> new Transform2158().createAndShowGUI()); } } private static void runCLI() { Scanner scanner = new Scanner(System.in); System.out.print("请输入输入数字: "); String input = scanner.nextLine(); System.out.print("请输入从进制 (2, 8, 10, 16): "); int fromBase = scanner.nextInt(); System.out.print("请输入到进制 (2, 8, 10, 16): "); int toBase = scanner.nextInt(); if (isValidBase(fromBase) && isValidBase(toBase)) { String result = convertBase(input, fromBase, toBase); if (result != null) { System.out.println("转换结果: " + result); } else { System.out.println("输入的数字在指定的进制中无效。"); } } else { System.out.println("无效的进制,请输入 (2, 8, 10, 16)。"); } scanner.close(); } private void createAndShowGUI() { JFrame frame = new JFrame("进制转换器"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 200); frame.setLayout(null); JButton button = new JButton("开始转换"); button.setBounds(80, 70, 140, 30); button.addActionListener(new ConvertAction()); frame.add(button); frame.setVisible(true); } private static class ConvertAction implements ActionListener { @Override public void actionPerformed(ActionEvent e) { String input = JOptionPane.showInputDialog("请输入输入数字:"); if (input == null) return; String fromBaseStr = JOptionPane.showInputDialog("请输入从进制 (2, 8, 10, 16):"); if (fromBaseStr == null) return; String toBaseStr = JOptionPane.showInputDialog("请输入到进制 (2, 8, 10, 16):"); if (toBaseStr == null) return; try { int fromBase = Integer.parseInt(fromBaseStr); int toBase = Integer.parseInt(toBaseStr); if (isValidBase(fromBase) && isValidBase(toBase)) { String result = convertBase(input, fromBase, toBase); if (result != null) { JOptionPane.showMessageDialog(null, "转换结果: " + result); } else { JOptionPane.showMessageDialog(null, "输入的数字在指定的进制中无效。"); } } else { JOptionPane.showMessageDialog(null, "无效的进制,请输入 (2, 8, 10, 16)。"); } } catch (NumberFormatException ex) { JOptionPane.showMessageDialog(null, "输入的数字在指定的进制中无效。"); } } } }