Java数字转意大利语字符串问题:为何仅输出"due"而非全部列表
Hey there! Let's get your program to print the full list of Italian numbers instead of just "due". Here's what's going on and how to fix it:
What's Causing the Issue
Right now, your main method only targets the number 2 and calls numberM(num) once. That's why you're only seeing "due" — the program isn't looping through all the numbers you want to output.
Solution 1: Iterate Through the Enum (Cleanest Approach)
Since you already have an enum NumberInWords that contains all your target words, you can directly loop through its values to print everything:
public static void main(String[] args) { // Loop through every value in the NumberInWords enum for (NumberInWords number : NumberInWords.values()) { System.out.println(number); } }
This will output all five words in order without having to handle index math at all.
Solution 2: Use Your convertNumberToString Method
If you want to use the string array-based method you wrote, update your main method to loop from 1 to 5 and call convertNumberToString each time:
public static void main(String[] args) { // Loop through numbers 1 to 5 and convert each to its Italian word for (int i = 1; i <= 5; i++) { convertNumberToString(i); } }
Bonus: Simplify Your convertNumberToString Method
You can also clean up that method — the entire chain of if-else checks is redundant, since you're already pulling the value directly from the array. Here's the simplified version:
public static String convertNumberToString(Integer i) { String[] ItNums = { "", "uno", "due", "tres", "quattro", "clinque" }; String myString = ItNums[i]; System.out.println(myString); return myString; }
Either solution will make your program output the full list: uno, due, tres, quattro, clinque.
内容的提问来源于stack exchange,提问作者Ryan Clarke

