1

I have a code is written that is supposed to print each of the numbers separately. Heres an example.

printDigits(1362) prints
2
6
3
1

printsDigits(985) prints
5
8
9

You can pull apart a number into its digits using / 10 and % 10.

I have started some code the way I was taught but I am not sure what to do with the other variables. Please have a look:

public class Main {

  public static void main(String[] args) {
    System.out.println(printDigits(1362));
    System.out.println(printDigits(985));
    }

  public static int printDigits(int x){
    int y = x % 10;
    while (x > 0){
      x = y;
      System.out.println(x);
      x = x / 10;
    }
   return x;
   }
}
SuleymanSah
  • 17,153
  • 5
  • 33
  • 54
roxxy
  • 19
  • 1
  • 5

5 Answers5

1

Why don't you convert the parameter x to String then read each Char in the String since a String is array of Char. If the output must be an int you convert the Char to int.

Eliano
  • 23
  • 2
0

You need to write int y = x % 10; inside the loop to "pull apart" every digit and print the digit y you have "pulled out". Remove the System.out.println around your function calls. You don't need to return a number, so you can change your return type to void:

public class Main {
    public static void main(String[] args) {
        printDigits(1362);
        System.out.println();
        printDigits(985);
    }

    public static void printDigits(int x) {
        while (x > 0) {
            int y = x % 10;
            System.out.println(y);
            x = x / 10;
        }
    }
}
tobsob
  • 602
  • 9
  • 22
0

printDigits method should be like this:

public static void printDigits(int x) {
    int y;
    while (x > 0) {
        y = x % 10;
        System.out.println(y);
        x = x / 10;
    }
}

And the calling of the method will be like this:

printDigits(1362); // without the System.out.println()
Mushif Ali Nawaz
  • 3,707
  • 3
  • 18
  • 31
0

There are various ways to achieve such results. You can better understand all solutions in these answers.

Usama Azam
  • 403
  • 5
  • 13
0
public static void printDigits(int num) {
    while(num>0) {
        int remainder = num%10;
        num = num/10;
        System.out.println(remainder);
        printDigits(num);
    }

}

You can use recursion to make it even more efficient.

VSharma
  • 471
  • 4
  • 8