Tushar Muralidharan
Tushar Muralidharan

Reputation: 15

Why is this Digits Display program not working?

My goal is to output something like this:

Enter a number: 789

7

8

9

Using loop structures and basic strings.

Here is my program atm.

public static void main(String[] args) {

    int mod;
    int power = 10;
    int display;
    String number;
    Scanner input = new Scanner(System.in);

    System.out.println ("Enter a positive integer: ");
        number = input.nextLine();

    int numberLength;

    numberLength = number.length();
    numberLength -= 1;

    do {

        mod = Math.pow (power, numberLength);
        power -= 1;
        display = number % mod;
        System.out.println (display);

    } while (mod>=1);       
}

}

Any help will be appreciated! Thanks!

Upvotes: 1

Views: 89

Answers (2)

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59996

No need to any loop or any thing you can use replace("", "\n"); in one step you can use System.out.print(number.replace("", "\n")); for example :

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter a positive integer: ");//789
    String number = input.nextLine();
    System.out.print(number.replace("", "\n"));
}

Output

Enter a positive integer: 789

7
8
9

Upvotes: 2

Jens
Jens

Reputation: 69460

use String.charAt()

        String number;
        Scanner input = new Scanner(System.in);

        System.out.println ("Enter a positive integer: ");
            number = input.nextLine();

            for (int i=0; i<number.length();i++) {
                System.out.println(number.charAt(i));
            }

Upvotes: 0

Related Questions