Armitage Armitage - 1 year ago 68
Java Question

Using the Scanner class in Java to get specific digits of an integer

I just started learning Java (two months and counting), and I still have lots of questions and a whole lot to learn. Right now I want to use the

class to "divide" an integer into its digits. I'll explain myself better with an example:

I request the user to type a four-digit integer, say
. What I want to do is to use the
class to divide that integer and to assign each one of its digits to a variable; i.e.
a = 8
b = 9
c = 1
d = 9

I positively know that it can be done and that the
class is the way to go. I just don't know how to properly use it. Can a noob in need get some help here? Thanks!

Answer Source

You can use a delimiter with the scanner. You can use an empty string as delimiter for this case.

String input = "8919";
Scanner s = new Scanner(input).useDelimiter("");
a = s.nextInt();
b = s.nextInt();
c = s.nextInt();
d = s.nextInt();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download