Write a program that reads in an integer and breaks it into a sequence of indivi
ID: 3624886 • Letter: W
Question
Write a program that reads in an integer and breaks it into a sequence of individual digits in reverse order. For example, the input 16384 is displayed as4
8
3
6
1
You may assume that the input has no more than five digits and is not negative.
Declare a class DigitExtractor:
public class DigitExtractor
{
/**
Constructs a digit extractor that gets the digits
of an integer in reverse order.
@param anInteger the integer to break up into digits
*/
public DigitExtractor(int anInteger) { . . . }
/**
Returns the next digit to be extracted.
@return the next digit
*/
public int nextDigit() { . . . }
}
In your main class DigitPrinter, call System.out.println(myExtractor.nextDigit()) five times.
Here are sample program runs:
Please enter a 5 digit integer: 16384
4
8
3
6
1
Please enter a 5 digit integer: 93476
6
7
4
3
9
Your main class should be called DigitPrinter.
Explanation / Answer
public class DigitExtractor
{
private int anInteger;
public DigitExtractor(int t)
{
anInteger=t;
}
public int nextDigit()
{
int a;
a=anInteger%10;
anInteger=anInteger/10;
return a;
}
}
======================================================================================
import java.util.Scanner;
public class DigitPrinter
{
public static void main(String args[])
{
Scanner a=new Scanner(System.in);
int b=a.nextInt();
int i;
DigitExtractor ob=new DigitExtractor(b);
for(i=1;i<=5;i++)
{
System.out.println(ob.nextDigit());
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.