You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何判断输入字符串是否为整数型字符串?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 single char as input, but you're passing the entire String (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 lowercase true.
  • Broken while loop 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 if check1 is true, spamming "Yes" nonstop—we only need to output the result once, not loop it.
  • 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:

  1. We start by assuming the string is all digits (isAllDigits = true).
  2. We loop through every character in the input string using charAt().
  3. If we find any character that isn't a digit, we set isAllDigits to false and break out of the loop early (no need to check the rest).
  4. Finally, we print "Yes" if all characters are digits, otherwise "No".

内容的提问来源于stack exchange,提问作者khillery83

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 13:17:30