Joan Joan - 2 months ago 10
Java Question

A java console program that converts decimal to binary without using a predefined method (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]);
}


Hi! this is my first question. I explored a bit about java, which I became recently interested in. I'm quite a beginner in java, honestly!

Using for, this is the solution I derived from other sources, but the problem here is the error, I've been thinking high and low, still I can't remove the "Error: incompatible types: possible lossy conversion from int to byte" from line[12] including the class declaration and the end class "}". oh! and I am using DrJava.

Is there something wrong with this program?

Answer

You are trying bin[a] = val%2; where val int type and bin[a] is byte type. byte is 8 bit where int is 32 bit. You are trying to enter a 32 bit value on 8 bit memory. That's why it it giving incompatible type error.

There are some issues in your code. After fixing them it works:

 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]);
  }
Comments