2

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!

EDIT:The suggestion that has been made does not match my specific question. In that thread the class Scanner is not used to separate the integer into digits. I specified i wanted to use the Scannerclass because many different methods used there are still way beyond my level. Anyway, there are lots of interesting ideas in that thread that i hope i will be able to use later, so thanks anyway.

Armitage
  • 21
  • 1
  • 6

3 Answers3

3

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(); 
0

you should read the integer as whole number and store it in a variable. after you stored it you can split it up. other way is so store it as string and then split the string. what you should choose depends on what youwant to do with it afterwards

Aelop
  • 156
  • 9
0

Try this:

import java.util.Scanner;

public class ScannerToTest {

    public static void main(String[] args) {

        int a,b,c,d;

        System.out.print("Please enter a 4 digit number : ");
        Scanner scanner = new Scanner(System.in);
        int number = scanner.nextInt();

        String numberToString = String.valueOf(number);

        if(numberToString.length() == 4) {
            String numberArray [] = numberToString.split("");
            a = Integer.parseInt(numberArray[1]);
            b = Integer.parseInt(numberArray[2]);
            c = Integer.parseInt(numberArray[3]);
            d = Integer.parseInt(numberArray[4]);
            System.out.println("Value of a is : " + a);
            System.out.println("Value of b is : " + b);
            System.out.println("Value of c is : " + c);
            System.out.println("Value of d is : " + d);
        }else {
            System.out.println("Numbers beyond 4 digits are disallowed!");
        }

    }

}
CodeWalker
  • 2,281
  • 4
  • 23
  • 50