Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

233
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda