I'm a beginner in Java and I have a question from the "Head First Java" book. In the book, the author creates a method that takes the number as String and then convert it into int. Why do I need to take the input as a string and convert it rather than directly take it as an int. Below is he screenshot that I'm talking about.
Simply because the user's guess is most probably entered through a mechanism which only supports entering chars, or strings, but no other types. For example,
most GUIs have a text-input control, but not a numeric input control. So, the user enters text in the control, and then the program must convert the text to a number.
To me, this example is highlighting a very important point:
Users cannot enter "Integer" values.
Nor Dates, Decimals, Floats or any other Data Type ...
... except good, old-fashioned Strings that just happen to look like values in other Data Types.
Once you accept that the user can only work in Strings and that your application works in proper Data Types, your mind will be in a very Good Place to overcome a huge number of potential run-time bugs when working with User input.
Always "format" values as you put them in front of the user and "un-format" values as you read them back. Assume that everything supplied by the User is inherently tainted and needs to be validated and verified. (e.g. is "q" numeric? How about "e"? Different languages; different tolerances).
You need to see this not from the point of view of your program code, but from the point of view of the user, who use a keyboard with about 100 keys, and who will be happily tapping on these keys. Your program then has to make sense of it.
If you tried to read just an integer, you couldn't for example distinguish between 0, +0 and -0. You couldn't distinguish between phone numbers with 0, 1 or 2 leading zeroes which are actually very, very different. You couldn't let a user enter 12cm or 12in or 12 inch. Or $12.34. Or enter dress sizes and one dress has size 12-14 instead of just a number (and no, that's not a -2, it's between size 12 and size 14
And there has been a study about severe problems with the data produced by some biologists where entering strings like 1234567e1 were interpreted as numbers instead of strings. Or someone had things called 3JAL1985, 3JAM1985 and 3JAN1985 and the first two were taken as strings and the last one as a date. So it is very important that you know how to treat any input correctly. Beyond just trying to read a number.
That is the best practice, because when you read the users input as string, you can use a try...catch block to detect whether the users input qualifies to be an integer. This is done by using Integer.parseInt() method to convert the string to an integer. But when you receive the input directly as int, and in case the user enters a string of characters, your program will crash. Hope you get what I'm saying.