2016-02-10 52 views
1

我設法使用堆棧來打印十進制到二進制,但我不知道如何分離二進制每4返回,這意味着這一點。如果我想要123 = 1111011的二進制數就是打印出來的東西,我希望它打印出1111 011等等每4位數字。讓我知道它是否可以完成,請嘗試示範它,如果你可以嘗試學習!如何在java中分離二進制打印輸出?

import java.util.*; 
public class SchoolHomework { 

/** 
* @param args the command line arguments 
*/ 
public static void main(String[] args) { 
    System.out.println("Program that converts decimal to binary!"); 
    int dec; 
    System.out.println("Please type in a decimal number:"); 
    Scanner input = new Scanner(System.in); 
    Stack<Integer> todec = new Stack<Integer>(); 
    dec = input.nextInt(); 
    if (dec < 0){ 
     System.out.println("Error: Please enter a positive number!"); 
     System.exit(0); 
    } 
    while (dec != 0){ 
     int stackv = dec % 2; 
     todec.push(stackv); 
     dec /= 2; 

    } 
    System.out.println(dec + " To binary is: "); 
    int counter = 0; 
    while (!(todec.isEmpty())) { 
     String val = todec.pop().toString(); 
     System.out.print(val); 
     counter = counter + 1; 
     if (counter >= 4){ 
      counter = 0; 
      System.out.print(" "); 
     } 

    } 
} 
} 

回答

0

所以大家如果你想知道,我想通了。我使用了一個tostring,像這樣String val = todec.pop()。toString();這解決了我的問題!

0

在last while循環中使用一個計數器(從4到0或反之亦然)。

Psudo代碼

counter = 0 
while todec is not empty 
    print todec entry 

    counter = counter + 1 
    if counter >= 4 then 
     counter = 0 
     print " " 
    endif 
end while 

你最好使用shift operator而不是 「格」 或 「MOD」 運營商

+0

你能解釋一下你的,而不是 「格」 或 「MOD」 – JimBob101

+0

是什麼意思另外,當我實施這種變化時,我沒有得到正確的二元回報。你知道爲什麼嗎?我用新的代碼編輯了初始文章! – JimBob101

+0

對於這兩個問題:因爲你正在使用'div'運算符,所以'123/2 = 61.5'投射到Integer會丟掉一些比特。更改使用移位操作符將解決您的問題。 – sdao