Printing each digit of a number using a for loop

Viewed 434

I have an assignment where I have to print each digit while using a for loop and I am very confused. I know that the code I have written is VERY wrong for many reasons, but I'm having a lot of trouble piecing together the various skills we have been learning. How can I fix my code so that 365 is printed as 3 6 5?

class Main {
    method1(365);

    public static void main(String[] args) {
    }

    String number = String.valueOf(num);

    public int method1(int num) {
        for (int i = 0; i < number.length(); i++) {
            int j = Character.digit(number.charAt(i), 10);
            System.out.print("digit: " + j);
        }
    }
}
2 Answers

You need to re-order your code in correct syntax and order to make it work correctly,

  1. call the method1(365) inside the main method
  2. you have to make the method1(365) method static to be accessible as class method.
  3. After converting int number to String then access each character of digit by charAt
  4. you can use int j = Character.digit(number.charAt(i), 10); to convert the character to a digit by base of 10 or simpley use int j = Character.getNumericValue(number.charAt(i)); which will be default on base of 10.
public static void main(String[] args) {
    method1(365);
}

public static void method1(int num) {
    String number = String.valueOf(num);
    for (int i = 0; i < number.length(); i++) {
        int j = Character.digit(number.charAt(i), 10);
     // int j = Character.getNumericValue(number.charAt(i));
        System.out.print("digit:" + j + " ");
    }
}

Since Java 9 you can use codePoints method:

int number = 365;
String.valueOf(number)
        // IntStream
        .codePoints()
        // Stream<String>
        .mapToObj(Character::toString)
        // print in a column
        .forEach(j -> System.out.println("digit: " + j));

Output:

digit: 3
digit: 6
digit: 5

See also: Converting Int value to List of Integer digits

Related