smdj92
smdj92

Reputation: 1

Putting the Digits of an int into an Array using Java?

I want to separate int values that are provided via user input. For example, when entering 153 I want to extract each digit (3 then 5 then 1 or vice versa) and stick all of them into an int[].

So far I have used the modulus operator to extract the last digit, but I still need to extract all the previous digits so I can proceed to test whether the int given by the user is narcissistic or not.

The reason for doing this is so that I can test whether the user has inputted a narcissistic number. The program will return true or false depending on the input.

public class narc {

    public static void main(String[] args){
         Scanner myScan = new Scanner(System.in);
         System.out.println("enter number: ");
         int digit = myScan.nextInt();
         String s1 = Integer.toString(digit);
         System.out.println(narcNumber(digit));
   }

   public static boolean narcNumber(int number) {
       System.out.println(number%10);
       return false;
   }
}

So far, narcNumber(num) only returns the last digit of the given number.

Upvotes: 0

Views: 137

Answers (2)

vincrichaud
vincrichaud

Reputation: 2208

If you still want to use modulus to get the digits :

List<Integer> digits = new ArrayList<Integer>();
while(inputNumber > 0) {
    currentDigit = inputNumber % 10;
    digits.add(currentDigit);
    inputNumber = inputNumber / 10;
}

Upvotes: 0

devgianlu
devgianlu

Reputation: 1580

int[] split = new int[s1.length()];
for (int i = 0; i < split.length; i++) {
    split[i] = Character.getNumericValue(s1.charAt(i));
}

split will contain all numbers of the input number.

Upvotes: 3

Related Questions