How about a readln for numbers?

Cay Horstmann cay.horstmann at gmail.com
Thu Nov 7 19:41:09 UTC 2024


In Python, this is not so different. You need to parse the input string.

loan = float(input("Loan: "))

I think it is fine to have students understand that I/O is fundamentally text, and that the text needs to be parsed. And that there may be more than one choice of parsing. When I taught in Germany, my students were very aware of the difference between the "correct" number format (e.g. 1.000,00 for a loan of a thousand euro) and the "American" way (1,000.00).

I have a different issue with

var loan = Double.parseDouble(readln("Loan: "));

Now I need to tell students at a very early point that most static methods have a class name (Double.parseDouble, Math.sin), but a privileged few don't (readln). Just the kind of accidental complexity we want to move away from.

One solution is more privileged static methods:

var loan = parseDouble(readln("Loan: "));

Another solution is not to have privileged I/O methods:

var loan = Double.parse(IO.in("Loan: "));

(renaming the methods for brevity).

Cheers,

Cay

On 07/11/2024 17:33, Kenneth Fogel wrote:
> The readln method introduced as part java.base is great because it includes the prompt for the input. The only shortcoming is that if the input must be a number then you still need to employ a static class member such as Double.parseDouble() to make it a number:
> 
> // Currently
> 
> var loan = Double.parseDouble(readln("Loan: "));
> 
> // My delusional idea
> 
> var loan = readDbl("Loan: ");
> 
> I can think of reasons why this could be a bad idea. I taught my students to use a construct using Scanner to create a console input that passed my Beethoven test (while humming Beethoven’s 5^th symphony randomly strike keys on your keyboard as if you were playing the symphony and your code should just report invalid input and not an exception). If we had a readInt and/or readDbl they would not pass this test. That Python would happily accept anything and then fail when the value was used in a calculation is no better. But, for learning Java could we have a readInt or readDbl alongside readln? I know that DataInputStream has such methods, but without a prompt and it must be attached to an input stream such as a file.
> 
> As always, just thinking out loud. Feel free to use my name in vain.
> 
> Ken
> 

-- 

Cay S. Horstmann | https://horstmann.com



More information about the discuss mailing list