Java二进制转十进制:如何实现输入校验与多次转换功能
Hey there! Let's fix up your binary-to-decimal converter with the two features you need. First, a quick note on your current code: using int to store the binary number can lead to overflow if the input is a long binary string (like 16+ bits). Switching to String will make this tool way more robust. Let's break down each solution step by step:
1. Validate Binary Input
To ensure the user only enters valid binary digits (0s and 1s), here's what to do:
- Use
Stringinstead ofintfor input: This avoids overflow and makes it easier to check each character. - Check every character: You can use a regular expression to match valid binary patterns, or loop through each character in the string to verify it's either '0' or '1'.
- Handle invalid input: If the input fails validation, print an error message and exit the program (per your request to terminate on invalid input).
2. Add Repeat Conversion Functionality
To let users convert multiple times without restarting the program:
- Wrap the entire workflow in a loop: A
do-whileloop works perfectly here because we want to run the conversion at least once, then ask if the user wants to go again. - Prompt for continuation: After each conversion, ask the user if they want to convert another binary number. Check their response (like "y" or "n") to decide whether to continue the loop or exit.
Complete Updated Code
import java.util.Scanner; public class BinaryToDecimalConverter { public static void main(String[] args) { Scanner input = new Scanner(System.in); String continueChoice; // Do-while loop for repeated conversions do { System.out.println("Enter a binary number: "); String binaryStr = input.nextLine().trim(); // Validate binary input if (!isValidBinary(binaryStr)) { System.err.println("Error: Invalid binary number! Only 0s and 1s are allowed."); input.close(); return; // Terminate program on invalid input } // Convert binary string to decimal int decimal = convertBinaryToDecimal(binaryStr); System.out.printf("Binary = %s | Decimal = %d%n", binaryStr, decimal); // Ask user if they want to continue System.out.println("Do you want to convert another binary number? (y/n): "); continueChoice = input.nextLine().trim().toLowerCase(); } while (continueChoice.equals("y")); System.out.println("Exiting program. Thanks for using the converter!"); input.close(); } // Helper method to validate binary string private static boolean isValidBinary(String binaryStr) { // Reject empty input if (binaryStr.isEmpty()) { return false; } // Regex to match only strings containing 0s and 1s return binaryStr.matches("^[01]+$"); } // Helper method to convert binary string to decimal private static int convertBinaryToDecimal(String binaryStr) { int decimal = 0; int length = binaryStr.length(); // Iterate over each character to calculate decimal value for (int i = 0; i < length; i++) { char bit = binaryStr.charAt(i); // Shift current decimal value left (multiply by 2) and add the current bit decimal = decimal * 2 + (bit - '0'); } return decimal; } }
Key Improvements Explained
- Input Validation: The
isValidBinarymethod uses a regex^[01]+$to ensure the input only contains 0s and 1s, plus checks for empty input. - Repeat Conversions: The
do-whileloop ensures the converter runs at least once, then continues as long as the user selects "y". - Robust Conversion: Using
Stringfor input avoids integer overflow, and the conversion logic uses integer arithmetic instead ofMath.powto prevent floating-point inaccuracies.
内容的提问来源于stack exchange,提问作者Henri Wurm
相关产品推荐
相关产品推荐

