0

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.

2
  • I now need to extract all other numbers input by the user separately -- Use a loop for it. Plenty of solutions out there on the net to achieve this. Commented Apr 19, 2019 at 14:08
  • For other digits in a single number, you can just read the number as a string, and use String.charAt() to extract the digits. Commented Apr 19, 2019 at 14:10

2 Answers 2

3
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.

Sign up to request clarification or add additional context in comments.

Comments

0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.