Hello I have a program that successfully converts decimal to binary. However, at the end the code divides 0 by 0 resulting in an error message at the end. Here's the code.
import java.lang.*;
import java.util.*;
public class BinaryConverter {
public static void main (String[] argv) {
Scanner input = new Scanner (System.in);
int number = 0;
int factorOfTwo = 0;
do {
System.out.println("Enter the number to convert (0-255): ");
number = input.nextInt();
} while (number< 0 || number > 255);
System.out.println("The number " + number + " converted to binary is : ");
for (factorOfTwo = 1; factorOfTwo <= 128; factorOfTwo*=2) {
if (number / factorOfTwo >= 1){
System.out.print("1");
number -= factorOfTwo;
}
else System.out.print ("0");
}
} // end of main
}// end of class
There is no division by zero in the posted code. There is only one division and factorOfTwo
can never be 0 in that loop.
If you still get division by zero error, make sure that you are running on this code:
Check that the compiled class file is newer the source file.
Check that the compiled class file is first in the classpath.
Also, note Aki's comment. You are creating the binary number backwards.