+ 2

Code for code coach No numerals not working properly

import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String n=sc.nextLine(); if(n.contains("1")){ n=n.replace("1","one"); } else if(n.contains("2")){ n=n.replace("2","two"); } else if(n.contains("3")){ n=n.replace("3","three"); } else if(n.contains("4")){ n=n.replace("4","four"); } else if(n.contains("5")){ n=n.replace("5","five"); } else if(n.contains("6")){ n=n.replace("6","six"); } else if(n.contains("7")){ n=n.replace("7","seven"); } else if(n.contains("8")){ n=n.replace("8","eight"); } else if(n.contains("9")){ n=n.replace("9","nine"); } else{ n=n.replace("10","ten"); } System.out.print(n); } }

30th May 2020, 2:37 PM
Shivam Rawal
2 odpowiedzi
+ 3
I don't know Java too well, but it seems to me that this if statement goes only once and changes the first encountered number. Perhaps you shouldn't use "else" here. Or think of doing it in a loop or something.
30th May 2020, 2:41 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 1
That's it, use a switch without any break instead! (any it's obviously required to start with the ten!)
31st May 2020, 1:33 AM
Sandra Meyer
Sandra Meyer - avatar