2014-12-04 665 views
-1

我想創建二進制計算器,將整數轉換爲8位二進制輸出。 我迷路了,任何幫助,將不勝感激。 這是迄今爲止我的進步:二進制計算器

import java.util.Scanner; 
import java.lang.Math; 
public class Unit4 
{ 
    public static int convertToBinary(int baseTenIntOne) 
    { 
     int [] firstNum = new int [8]; 
     int binary = 0; 
     int bvalue = 1; 
     for (int i = 0; i < 8; i++) 
     { 
      if (baseTenIntOne % 2 == 1) 
       binary += bvalue; 
      else 
       binary += 0;  
      bvalue *= 10; 
     } 
     System.out.println(binary); 
     return binary; 
    } 
    public static void main(String[]args) 
    { 
     Scanner scan = new Scanner(System.in); 
     int baseTenIntOne; 
     int baseTenIntTwo; 
     System.out.println("Enter a base ten number between 0 and 255, inclusive."); 
     baseTenIntOne = scan.nextInt(); 
     System.out.println(baseTenIntOne); 
     System.out.println("Enter a base ten number between 0 and 255, inclusive."); 
     baseTenIntTwo = scan.nextInt(); 
     System.out.println(baseTenIntTwo); 
     convertToBinary(baseTenIntOne); 
    } 
} 

回答

0

嘗試使用Integer.toBinaryString(int i);

然後追加零到字符串的開頭

public static String convertToBinary(int baseTenIntOne){ 
    String binaryRep = Integer.toBinaryString(baseTenIntOne); 
    while(binaryRep.length()<8){ 
     binaryRep.insert(0, "0"); 
    } 

    return binaryRep; 
    } 
1

你可以把這個片段在convertToBinary(INT baseTenIntOne)方法

{

if (baseTenIntOne == 0) 
{ 

    return "0"; 
} 

String binary = ""; 
while (baseTenIntOne > 0) { 
    int rem = baseTenIntOne % 2; 
    binary = rem + binary; 
    baseTenIntOne = baseTenIntOne/2; 
} 
System.out.println(binary); 
return binary; 

}

0

忘記正在做的for循環:

baseTenIntOne /= 2; 

那麼下一個位出現在第一個位置。

1

您可以使用下面的方法:

System.out.println("Enter a Integer Value:"); 
int h = Integer.parseInt(br.readLine()); 
String oct = Integer.toString(h,8);