Complete Question:
Write a while (or for) statement to print all the digits of an int type variable x, one digit per line For example, if int x 38625, then the output should be in 5 lines as 60 (Hint: You may use built-in method to get a String representation of x then print out each character in String)
***** Java *****
Answer:
import java.util.*;
public class Main{
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int x = input.nextInt();
String str = Integer.toString(x);
for(int i =0;i<str.length();i++) {
System.out.println(str.charAt(i));
}
}
}
Step-by-step explanation:
This line prompts user for input
System.out.print("Enter an integer: ");
This line gets user input
int x = input.nextInt();
This line converts user input to string
String str = Integer.toString(x);
The following loop iterates through the converted string
for(int i =0;i<str.length();i++) {
This prints each character on the string
System.out.println(str.charAt(i));
}