如何判断输入字符串是否为整数型字符串?Java代码错误排查求助
Issues in Your Java Code & Fixed Version
Let's walk through the problems in your code one by one, then fix it to meet your requirement:
Key Errors in Your Current Code
- Wrong parameter for
Character.isDigit(): This method requires a singlecharas input, but you're passing the entireString(userString). This will cause a compile error immediately because the method signature doesn't match. You need to check every character in the string individually, not the whole string at once. - Incorrect boolean literal: Java is case-sensitive, so
True(capital T) is invalid. The correct boolean value is lowercasetrue. - Broken
whileloop logic:- You used an assignment operator
=instead of the equality check==in the loop condition. Even if you fixed that, this loop would run infinitely ifcheck1istrue, spamming "Yes" nonstop—we only need to output the result once, not loop it.
- You used an assignment operator
- Incomplete validation: Your code doesn't actually check all characters in the string. It only attempts a single (invalid) check, so it can't correctly determine if every character is a digit.
Fixed Code
import java.util.Scanner; public class LabProgram { public static void main(String[] args) { Scanner scnr = new Scanner(System.in); String userString = scnr.next(); boolean isAllDigits = true; // Assume valid until proven otherwise // Loop through each character in the string for (int i = 0; i < userString.length(); i++) { char currentChar = userString.charAt(i); if (!Character.isDigit(currentChar)) { isAllDigits = false; break; // No need to check further once we find a non-digit } } // Output the result based on our check if (isAllDigits) { System.out.println("Yes"); } else { System.out.println("No"); } scnr.close(); // Good practice to close the scanner } }
How the Fixed Code Works:
- We start by assuming the string is all digits (
isAllDigits = true). - We loop through every character in the input string using
charAt(). - If we find any character that isn't a digit, we set
isAllDigitstofalseand break out of the loop early (no need to check the rest). - Finally, we print "Yes" if all characters are digits, otherwise "No".
内容的提问来源于stack exchange,提问作者khillery83
相关产品推荐
相关产品推荐

