• Post Reply Bookmark Topic Watch Topic
  • New Topic

Taking user input as String instead of Integer  RSS feed

 
James Allen A.
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm doing an exercise out of the Head First Java book and it decides to take the users input as a String rather than an Int and parse it later. First, is this a general convention? If so, why?
 
fred rosenberger
lowercase baba
Bartender
Posts: 12565
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
so here is a question...what do you think should happen if you tried to take it as an integer, and the user input "fred"?

remember, the user is able to type just about anything they want...alphabetics, digits, symbols...

Now, what happens if you write your code to always expect a String as input, and they type stuff?
 
Wayan Saryada
Ranch Hand
Posts: 119
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You don't have to always to take the string as an input and parse them later to the required data type. If you want an integer in the first place you can also take the input as an int. For example you can use the Scanner.nextInt() method. But as Fred mentioned in his answer that user can input any characters, you have to validate if user input the correct data. One thing you can also do is to give an informative label to show what kind of data should be entered by the user. Although this doesn't stop them from entering invalid data, at least the user know what data is expected by your application.
 
James Allen A.
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the explanation Wayan and Fred. Very clear now.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!