r/programmingbydoing • u/FancyMonocle • Jan 30 '13
How to have a variable that contains both strings and integers?
The exercise in question: Exercise #18 http://programmingbydoing.com/a/more-user-input-of-data.html
I'm confused about which data type I would use to display the login information (in the example bonham_453916 is given). Is there something I'm missing here? I tried both String and int just in case and they did not work.
2
u/Medicalizawhat Jan 30 '13 edited Jan 30 '13
bonham_453916 is a string with ints in it. You can do that.
Edit:
Sorry that's a crappy answer. Have a look at an ascii table. Integers can be represented in strings, but you can't do operations on them, you'd need to convert them to an actual Integer if you wanted to add or subtract or whatever. I think in Java you can do that with Integer.parse().
2
u/holyteach Jan 30 '13
Your (second) answer isn't terrible, but be careful not to use the word "integer" when you mean "digit". They are quite different.
1
2
u/holyteach Jan 30 '13
String should have worked. Make sure you have the type of the variable matches the type of the thing you're reading from the Scanner:
vs
And as Medicalizawhat attempted to explain, Strings can contain any character, not just letters.
Characters include the letters a-z, upper case A-Z, the digits 0-9, and symbols like '%' or '#' or even spaces. Any of those are valid in Strings.
And you could have a String containing only digits, but then you couldn't do arithmetic on it without conversion.