Java如何编写正确的if语句校验4位double字面量合法性
原有代码核心问题
- 逻辑顺序错误:第一个判断直接判定长度<=4就输出合法,后续所有校验规则完全没有执行
- 字符比较逻辑错误:char类型的数字字符(如
'0')的ASCII值为48,直接写j <= 9是将字符的ASCII码值和数字9比较,永远不会匹配到数字字符,需要改成j >= '0' && j <= '9' - 缺少核心校验逻辑:没有统计小数点出现次数、没有校验符号只能出现在首位、没有校验所有字符都属于允许的字符集
- 缺少边界保护:如果输入字符串长度不足4,调用
charAt会直接抛出数组越界异常 - 存在冗余无效变量:
i、n变量没有实际作用,相关逻辑无效
修正后完整实现
import java.util.Scanner; public class DoubleLiteralChecker { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); System.out.print("Enter a valid four character double literal: "); String doubleliteral = keyboard.nextLine().trim(); // 校验输入长度必须为4位 if (doubleliteral.length() != 4) { System.out.print("\n" + doubleliteral + " is not a valid four character double literal."); keyboard.close(); return; } int dotCount = 0; boolean isValid = true; for (int index = 0; index < doubleliteral.length(); index++) { char currentChar = doubleliteral.charAt(index); // 首位字符校验:允许为符号、小数点、数字 if (index == 0) { if (currentChar == '+' || currentChar == '-') { continue; } else if (currentChar == '.') { dotCount++; continue; } else if (currentChar >= '0' && currentChar <= '9') { continue; } isValid = false; break; } // 非首位字符校验:不允许出现符号,仅允许小数点、数字 else { if (currentChar == '+' || currentChar == '-') { isValid = false; break; } else if (currentChar == '.') { dotCount++; if (dotCount > 1) { isValid = false; break; } continue; } else if (currentChar >= '0' && currentChar <= '9') { continue; } isValid = false; break; } } // 最终校验小数点必须恰好出现1次 if (isValid && dotCount == 1) { System.out.print("\n" + doubleliteral + " is a valid four character double literal."); } else { System.out.print("\n" + doubleliteral + " is not a valid four character double literal."); } keyboard.close(); } }
内容的提问来源于stack exchange,提问作者Fried_Sauer.Kraut
相关产品推荐
相关产品推荐

