I’m a beginner coder trying to work on converter for words which should work that way:Input= “zero;six;eight;two” Output = “0682”. But in my case the output I get is “0282”. Are there any solutions to that? Or like maybe I should program differently?. I found that LinkedLists or HashMap could work, if so could you show how?
JavaScript
x
Scanner scanner = new Scanner(System.in);
String number = scanner.next();
while (true) {
String num = "";
if(number.contains("zero"))
num = num + "0";
if (number.contains("one"))
num = num + "1";
if (number.contains("two"))
num = num +"2";
if (number.contains("three"))
num = num + "3";
if(number.contains("four"))
num = num + "4";
if(number.contains("five"))
num = num + "5";
if(number.contains("six"))
num = num + "6";
if(number.contains("seven"))
num = num + "7";
if(number.contains("eight"))
num = num + "8";
System.out.println(number);
System.out.println(num);
break;
}
Advertisement
Answer
You should be splitting your semicolon-separated input on ;
, and then iterating each term in a loop:
JavaScript
Scanner scanner = new Scanner(System.in);
String input = scanner.next();
String[] nums = input.split(";");
String num = "";
for (String number : nums) {
if ("zero".equals(number))
num = num + "0";
else if ("one".equals(number))
num = num + "1";
else if ("two".equals(number))
num = num + "2";
else if ("three".equals(number))
num = num + "3";
else if ("four".equals(number))
num = num + "4";
else if ("five".equals(number))
num = num + "5";
else if ("six".equals(number))
num = num + "6";
else if ("seven".equals(number))
num = num + "7";
else if ("eight".equals(number))
num = num + "8";
else if ("nine".equals(number))
num = num + "9";
}
System.out.println("input: " + input);
System.out.println("output: " + num);
For an input of zero;six;eight;two
this was the output from the above script:
JavaScript
input: zero;six;eight;two
output: 0682