一个java控制台程序,它将十进制转换为二进制而不使用预定义的方法(for)

public static void main(String [] args){ byte bin[] = new byte[255]; int a; System.out.print("Enter Number: "); System.in.read(bin); Integer val= Integer.parseInt(new String(bin).trim()); for(a=1; val >= 0;a++){ bin[a] = val%2; val = val/2; } System.out.println("Binary: "); for(int i = a-1;i >= 0;i--){ System.out.print(bin[i]); } 

嗨! 这是我的第一个问题。 我探讨了一些关于java的问题,我最近对此感兴趣。老实说,我是java的初学者!

使用for,这是我从其他来源获得的解决方案,但这里的问题是错误,我一直在思考高低,我仍然无法删除“错误:不兼容的类型:从int到byte的可能有损转换“来自第[12]行,包括类声明和结束类”}“。 哦! 我正在使用DrJava。

这个程序有问题吗?

你正在尝试bin[a] = val%2; 其中val 整数类型和bin[a]字节类型。 byte是8位 ,其中Integer是32位 。 您正尝试在8位内存上输入32位值。 这就是它给出不兼容类型错误的原因。

您的代码中存在一些问题。 修复后,它有效:

  byte bin[] = new byte[255]; int a; System.out.print("Enter Number: "); System.in.read(bin); Integer val= Integer.parseInt(new String(bin).trim()); Integer temp = val; // keep val intact if you want to print it later // Not temp >= 0, it'll run infinite. Also a=0, because later you are printing upto 0 for (a = 0; temp > 0; a++) { // temp % 2 returns int which doesn't support byte casting bin[a] = new Integer(temp % 2).byteValue(); temp = temp / 2; } // print binary number System.out.print("Binary of " + val + " is = "); for (int i = a - 1; i >= 0; i--) { System.out.print(bin[i]); } 

您的代码存在一些问题,但我已对其进行了更正,并添加了注释以获取有关更改的更多信息,此代码也可以使用。 试试吧!

 import java.util.Scanner; class Binary { public static void main(String [] args) { try //Catching the Exception thrown by program is necessary when you use System.in.read(byte[]) so we have used it. { byte bin[] = new byte[255]; int a; System.out.print("Enter Number: "); System.in.read(bin); //Input will be converted to byte and stored in the byte array 'bin'. Integer val= Integer.parseInt(new String(bin).trim()); //Then you're converting it to Integer. int Original_val=val; //Storing the value of 'val' into another variable as it will be changed in the loop so for showing output(if you want to print it) it is required. int Bits[]=new int[255]; //Creating integer array where the output(bits 0 or 1 as per calculation) will be stored for(a=1; val > 0;a++) //Here you have written val >=0 which will make the loop into infinite loop so change it to val > 0. { Bits[a] = val%2; //Storing the output (Here Answer will be stored from array index '1' as we have started loop from 1. val = val/2; } System.out.println("Binary of "+ Original_val + " is "); //Here we have used original value because after calculation value of 'val' will be changed. for(int i = a-1;i > 0;i--) //Starting index for storing input is 1 in the loop for the calculation so we will print array till Array index '1' { System.out.print(Bits[i]); } } catch(Exception e) { System.out.println("Error: "+e); } } }