I have modified my code, I am making a decoder that decodes as follows:
“2” as “a”, “22” as “b”, “222” as “c”, “3” as “d” etc
I’ve written the following logic to implement it
Scanner input = new Scanner(System.in);
System.out.println("Please enter the string encoded with appropriate T9 encoding algorithm");
String lStr=input.nextLine();
String[] tokens=lStr.split("\\s|0");
System.out.printf("Number of elements are: %d\n The text entered is: ", tokens.length);
for(String token: tokens)
{
if(token.equals("2")){
output=token.replace("2", "a");
}
else if(token.equals("22")){
output=token.replace("22","b");
}
//etc
If I give it an input like 2022 222 it decodes it as “abc” which is right but I wanted it to print “a bc” whenever it encounters a 0 as if in 2022 222, how can I achieve that, ive used 0 as a token along with white space, how can I tell it to put a space after reading 0 in the string?
Help please!
String lStr=input.nextLine();is the problem. Try checking the value of lStr at runtime – it will be the value of the whole line (perhaps unsurprisingly given the name of the method).To continue with this approach, you’ll need to read the whole line in as you do, but then check each token (there’s a method to do this) for a match with your encoding scheme.
E.g. If you read a line in:
lStr = “2 22 222 2222”;
which won’t match your scheme at all – you don’t have a value coded up as “2 22” do you?
HTH.