69.1k views
0 votes
JAVA

Write a program which takes a positive int input from the user, then prints the digits of that number. You should separate the digits using spaces of line
breaks so they appear individually.
Sample run:
Enter a positive integer:
>2587

7
8
5
2

User Shakari
by
4.5k points

1 Answer

5 votes

Final answer:

The Java program provided uses a while loop to separate and print each digit of a positive integer entered by the user. Modulus and division operations are used to isolate and remove each digit from the number.

Step-by-step explanation:

The student is looking to write a program in Java that takes a positive integer as input from the user and prints out each digit of that number on separate lines. Here's a simple code snippet that accomplishes this:

import java.util.Scanner;

public class PrintDigits {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a positive integer:");
int number = scanner.nextInt();

while (number > 0) {
System.out.println(number % 10);
number /= 10;
}
}
}

This code uses a while loop to separate the digits of the input number. It prints the least significant digit by using the modulus operator (%) and then removes that digit by dividing the number by 10. The loop continues until there are no more digits left to print.

User Jan Kislinger
by
4.1k points