Reputation: 78
first of all sorry for the title, couldn't think of anything else. I'm currently finishing a project on JetBrains Hyperskill, the project is a unit converter where the user can convert weight, length and temperature units. I'm almost finished with the project, the conversion works fine, however I have a problem with user input.
I have an enum class that holds all units -
The user input is made out of following parts:
<number> +
<(unit name) or (degree + unit name) or (degrees + unit name)> +
<random word like "to" or "in"> +
<(unit name) or (degree + unit name) or (degrees + unit name)>
So, user can input something like:
But, also able to input this:
Each input is held in a variable and user types this in a single line
val amount = scan.toDouble()
- amount to convertval source = scan.nextLine().toUpperCase()
- this should read input like “celsius” and “degrees Celsius”val word = scan.next()
- random wordval target = scan.nextLine().toUpperCase()
- this too should read input like “celsius” and “degrees Celsius”These are the valid inputs for each unit type:
My question - How can I make next() or nextLine() work for both “Fahrenheit” and “degrees Fahrenheit” (valid input), but if the user types something else, error message prints in console like “Parse error”?
Upvotes: 0
Views: 559
Reputation: 19622
Is the "word" token really random? If it's either to or in then you could split the string on that, and then you'll have
<value> <source units>, <target units>
You could also use a regex if you know how to wrangle those, something like this
(\d+) (degree \w+|degrees \w+|\w+) \w+ (.+)
where you have each part you care about in a capturing group.
Or, for this case, you could just do a string replace on degrees
and degree
with a blank string to remove them (in that order, so you don't end up with random s
characters) - you don't care about the word, and once you do that everything looks like value unit word unit
and you can split them on spaces and process each token.
You have a few options! Also don't post code screenshots pls, paste it in - not everyone can read them
Upvotes: 2