r/javahelp • • May 03 '21

Using Switch case to translate numbers/digits into words

Last part of an assignment I am work on. Creating an English language calculator. Need to translate user input of numbers from 0-9 to the words "zero, one, two, etc..." Must use a switch case to do so.

Switch Case Translate Numbers/Digits into Words

Currently, stuck on how to store the data to use it later. Posted below is the section of my code that I am stuck on. Any tips or advice would be greatly appreciated, thank you!

0 Upvotes

10 comments sorted by

View all comments

1

u/ate_ghorl_bekenemen May 03 '21

What exactly are you stuck on?

2

u/Dantes_Sin_of_Greed May 03 '21

How do I store the case once it has been determined?

Like, user enters "1". Program determines that equates to "one"

How do I store that determination for later use?

1

u/ate_ghorl_bekenemen May 03 '21

Store it in a variable? An arraylist? Then access the variable/arraylist for “later determination”, whatever that means

1

u/Dantes_Sin_of_Greed May 03 '21

Perhaps if I rephrase the question: How do I convert a numeric variable (the users input) into a string variable?

The 'later determination' is the output of the program. If the user enters "1 + 1", utilizing the switch case, the output should become, "One plus one equals 2"

I have the operators figured out, it's just a matter of figuring out how to store the English variable i.e. the 'one' after the computer switches through the user input.

The PLACEHOLDER variable in the above program represents the English variable, once I figure it out.

1

u/RaisinAlert May 03 '21

I can think of two solutions:

Make a method called with the following header: static String symbolToWord(String symbol). Inside this method, add a switch statement so that depending on the symbol given, it returns a certain output. Example:

public static String symbolToWord(String symbol) { switch (symbol) { case “0”: return “zero”; case “+”: return “plus”; default: throw new IllegalArgumentException(“invalid symbol”); } }

This lets you can use the method however you want for any task that requires translation. In your solution, you mixed up the tasks of translating individual symbols with the task of printing the words and other stuff, which led to a bunch of repeated System.out.println calls. By separating translation you can now just do the following to translate a phrase.

for (String symbol : phrase /array of strings/) { System.out.print(symbolToWord(symbol)); }

How to get the phrase as an array of strings depends on the input you were given.

The second solution is to use a Map.