Java如何循环校验整数输入是否存在前导零且不使用字符串操作
前导零校验功能实现方案
前提说明
你当前使用Scanner.nextInt()读取输入的逻辑存在根本限制:该方法会自动丢弃十进制输入的前导零,最终拿到的int值无法区分原始输入是0012还是12,因此无论怎么拆分整数位都无法完成前导零校验。
方案一:完全无字符串操作的实现
全程通过字节流逐个读取字符判断,不涉及任何字符串相关操作:
import java.io.IOException; public class LeadingZeroCheck { public static void main(String[] args) throws IOException { boolean looper = true; int validNum = 0; while (looper) { System.out.println("Enter an integer"); int currentChar = System.in.read(); // 跳过前置空白字符 while (Character.isWhitespace(currentChar)) { currentChar = System.in.read(); } // 校验是否存在前导零:首字符为0且后面还有其他数字 if (currentChar == '0') { int nextChar = System.in.read(); // 清空当前行剩余输入,避免影响下一轮读取 while (nextChar != '\n' && nextChar != -1) { nextChar = System.in.read(); } System.out.println("输入存在前导零,请重新输入"); continue; } // 首字符合法,拼接生成整数 validNum = 0; while (Character.isDigit(currentChar)) { validNum = validNum * 10 + (currentChar - '0'); currentChar = System.in.read(); } // 清空行尾剩余字符 while (currentChar != '\n' && currentChar != -1) { currentChar = System.in.read(); } looper = false; } System.out.println("合法输入为:" + validNum); } }
方案二:字符串操作简洁实现(解决循环更新问题)
你之前遇到的字符串循环无法更新的问题是实现逻辑错误导致的,每次循环内部重新读取输入即可正常工作,代码更易维护:
import java.util.Scanner; public class LeadingZeroCheck { public static void main(String[] args) { Scanner key = new Scanner(System.in); int validNum = 0; boolean looper = true; while (looper) { System.out.println("Enter an integer"); // 每次循环重新读取新的输入字符串,不存在无法更新的问题 String input = key.nextLine().trim(); // 校验前导零:长度大于1且以0开头即为非法 if (input.length() > 1 && input.startsWith("0")) { System.out.println("输入存在前导零,请重新输入"); continue; } // 校验是否为合法整数 try { validNum = Integer.parseInt(input); looper = false; } catch (NumberFormatException e) { System.out.println("输入不是合法整数,请重新输入"); } } key.close(); System.out.println("合法输入为:" + validNum); } }
内容的提问来源于stack exchange,提问作者raxnocafi
相关产品推荐
相关产品推荐

