求助:基于Eclipse的十进制转二进制转换器类实现问题
Hey there! Let's get your decimal-to-binary converter assignment sorted out. Based on the algorithm you provided, here's a complete, working implementation of the DecToBinConverter class in Java (perfect for your Eclipse project):
Assignment Recap
First, let's restate the requirements clearly to make sure we cover everything:
- Create a class named
DecToBinConverter - Include a public static void method
printInBinary(int n) - Implement this algorithm:
- Initialize an empty
IntegerstackS - If
nis 0, output 0 - While
n > 0:
a. Calculaterem = n % 2
b. Pushremto stackS
c. Updaten = n / 2 - While stack
Sis not empty:
a. Pop a digit fromS
b. Print the digit
- Initialize an empty
Complete Implementation
import java.util.Stack; public class DecToBinConverter { public static void printInBinary(int n) { // Step 1: Initialize empty Integer stack Stack<Integer> binaryStack = new Stack<>(); // Step 2: Handle the special case where n is 0 if (n == 0) { System.out.println(0); return; } // Step 3: Push remainders to the stack as we divide by 2 while (n > 0) { int remainder = n % 2; binaryStack.push(remainder); n = n / 2; // Integer division automatically truncates the decimal } // Step 4: Pop digits from the stack to print the binary number in correct order while (!binaryStack.isEmpty()) { int digit = binaryStack.pop(); System.out.print(digit); } // Add a newline after the binary output for readability System.out.println(); } // Optional test method to verify functionality public static void main(String[] args) { // Test some common values printInBinary(0); // Output: 0 printInBinary(7); // Output: 111 printInBinary(16); // Output: 10000 printInBinary(42); // Output: 101010 } }
Key Notes
- Why the stack? When we divide by 2, we get the least significant bit first. The stack's LIFO (last-in, first-out) property lets us reverse this order to print the binary number from most to least significant bit.
- Special case for 0: If we didn't handle
n=0separately, the stack would stay empty and nothing would print—this fixes that. - Integer division: Using
n = n / 2works because integer division in Java automatically drops the fractional part, which is exactly what we need when converting decimal to binary.
Just drop this class into your Eclipse project, and it should meet all your assignment requirements. You can run the main method to test it with different values too!
内容的提问来源于stack exchange,提问作者TWangmo
相关产品推荐
相关产品推荐

