Question
Break a number into its individual digits, for example turn 1729 into 1, 7, 2,9. It is easy to get the last digit of a
Break a number into its individual digits, for example turn 1729 into 1, 7, 2,9. It is easy to get the last digit of a number n as n%10. But that gets the numbers in reverse order. Solve the problem with a stack. Your program should ask the user for an integer, then print the digits separated by spaces. Use the IntegerSplitterDemo provided.
import java.util.Scanner; public class IntegerSplitterDemo { public static void main(String[] args) { System.out.println("Please enter an integer to be split (0 to quit):"); Scanner in = new Scanner(System.in); int integer = 1; while (integer > 0) { integer = in.nextInt(); IntegerSplitter.split(integer); } } }
My program is this. But there is an error that I need to fix. Please help.
import java.util.Scanner;
import java.util.Stack;
/**
Class for splitting an integer into its individual digits.
*/
public class IntegerSplitter {
/**
Splits the given integer into its individual digits
and prints them to the screen.
@param number Integer to be split.
*/
public static void main(String[] args)
{
}
public static void IntegerSplitter(int num)
{
//declare stack
Stack stack = new Stack();
int n;
//use loop to push number into stack
for (int i = 0;;i++)
{
n = num % 10;
stack.push(n);
num = num / 10;
if (num == 0)
{
break;
}
}
while (!stack.empty())
{
System.out.print(stack.pop() + "");
}
}
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started