英文数字字符串转Integer异常求助:部分字符转换结果为0
Let’s work through why those specific number words are spitting out 0 and fix it without ditching your existing method—since you mentioned you have to stick with that approach.
Common Issues & Straightforward Fixes
First, let’s guess your current code looks something like this (super typical for this kind of manual conversion):
public static int convertWordToInt(String input) { if (input.equals("ONE")) return 1; if (input.equals("TWO")) return 2; if (input.equals("THREE")) return 3; if (input.equals("FOUR")) return 4; if (input.equals("SIX")) return 6; // Oops—missing checks for FIVE, SEVEN, EIGHT, NINE! return 0; }
Here’s what’s going wrong and how to fix each scenario:
Missing Condition Branches
The most likely culprit is that your if-else chain or switch statement doesn’t include explicit checks for those four number words. Any input that doesn’t hit a matched condition falls through to your defaultreturn 0.Fix: Add the missing checks. If you’re using if-else:
if (input.equals("FIVE")) return 5; if (input.equals("SEVEN")) return 7; if (input.equals("EIGHT")) return 8; if (input.equals("NINE")) return 9;Case Sensitivity Mismatch
If your code checks for lowercase ("five") but users input uppercase ("FIVE") or mixed case ("Five"), theequals()check will fail, leading to a 0 return.Fix: Normalize the input to a consistent case first, then compare. For example:
String normalizedInput = input.trim().toUpperCase(); // Trim whitespace too, just in case if (normalizedInput.equals("FIVE")) return 5; // Repeat this pattern for all number wordsIncorrect String Comparison
If you’re using==instead ofequals()(a common Java mistake), you’re comparing object references instead of the actual string content. This will almost always fail unless the input is the exact same string object.Fix: Replace any
==checks withequals()orequalsIgnoreCase().
Refactored Example (Keeping Your Original Structure)
Here’s how your fixed code might look, combining all these fixes to cover edge cases:
public static int convertWordToInt(String input) { // Handle null/empty input to avoid crashes if (input == null || input.trim().isEmpty()) { return 0; } String normalizedInput = input.trim().toUpperCase(); if (normalizedInput.equals("ONE")) return 1; if (normalizedInput.equals("TWO")) return 2; if (normalizedInput.equals("THREE")) return 3; if (normalizedInput.equals("FOUR")) return 4; if (normalizedInput.equals("FIVE")) return 5; if (normalizedInput.equals("SIX")) return 6; if (normalizedInput.equals("SEVEN")) return 7; if (normalizedInput.equals("EIGHT")) return 8; if (normalizedInput.equals("NINE")) return 9; // Default return for unrecognized inputs return 0; }
This should resolve the 0 returns for those four number words while keeping your original method structure intact.
内容的提问来源于stack exchange,提问作者Amr4AOT

