Armitage Armitage - 19 days ago 5
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

Scanner
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
8919
. What I want to do is to use the
Scanner
class to divide that integer and to assign each one of its digits to a variable; i.e.
a = 8
,
b = 9
,
c = 1
and
d = 9
.

I positively know that it can be done and that the
Scanner
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

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();
s.close();