我正在尝试创建二进制计算器,将整数转换为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 :(得分: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;
}
答案 1 :(得分:1)
您可以使用以下方法:
System.out.println("Enter a Integer Value:");
int h = Integer.parseInt(br.readLine());
String oct = Integer.toString(h,8);
答案 2 :(得分: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;
}
答案 3 :(得分:0)
Forgotten正在for-loop中进行:
baseTenIntOne /= 2;
所以下一位出现在第一个位置。