Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

225
Views
Printing each digit of a number using a for loop

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);
        }
    }
}
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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 + " ");
    }
}
over 4 years ago · Santiago Trujillo Report

0

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!