Return of the Java – 95 of 100 Days…
Just when I thought I was out, Java keeps pulling me BACK!
For more on this, watch the video a the bottom of the page!
I restarted a the KeepHydrated codewars challenge. Last time, I took a more long-winded approach and ended up lost. This time around I made it much smoother.
PSEUDOCODE
My new pseudocode for this challenge goes as follows:
- Import the Scanner class from Java
- Create Scanner object for obtaining input
- Prompt for time as a Double
- Multiply by .5
- Truncate the decimal using the toInt() methodÂ
- Display the liters of water consumed.
IMPORT THE SCANNER CLASS FOR OBTAINING USER INPUT
Last time, I used the readLine() method to obtain input from the keyboard. However, this is better for obtaining Strings than numbers.
Yes, the toInt() method allowed me to truncate the decimal from the user’s input. But while testing input using decimals, I found it could throw exceptions and crash the program.
By using the Scanner class, I could parse input for specific data types like doubles, float, etc. In this case, I could parse input for a double, store it, and do the math later.
MATH AND ROUNDING DOWN
Once I obtained the number of hours, all I had to do was multiply by .5 to get the amount of water. Finally, the toInt() method would truncate the decimal leaving us with the final answer rounded down!
I thought I could put my Java days behind me. Little did I know it still had some lessons for me. Kotlin doesn’t have a way to obtain decimals in terminal based programs.
The only option is to import the Scanner class from Java. From there, you can set up your program to get the type of input you want.
It took a lot of digging and experimenting to find this. I ran into a lot of errors, but I got there in the end.
Sure, I likely won’t use Kotlin for terminal based programs in my career. But this is an idea worth exploring. I gained some insight on different ways to use Kotlin and saw some connections with Java I didn’t know about.
Oh, and I’m definitely ready to complete the challenge on codewars.
Join the mailing list to see updates like this every week!
Coding Fanatic