I am trying to convert decimal to binary numbers from the user's input using Java.
I'm getting errors.
package reversedBinary;
import java.util.Scanner;
public class ReversedBinary {
public static void main(String[] args) {
int number;
Scanner in = new Scanner(System.in);
System.out.println("Enter a positive integer");
number=in.nextInt();
if (number <0)
System.out.println("Error: Not a positive integer");
else {
System.out.print("Convert to binary is:");
System.out.print(binaryform(number));
}
}
private static Object binaryform(int number) {
int remainder;
if (number <=1) {
System.out.print(number);
}
remainder= number %2;
binaryform(number >>1);
System.out.print(remainder);
{
return null;
} } }
How do I convert Decimal to Binary in Java?
Integer.toBinaryString()
is an in-built method and will do quite well.Binary to Decimal without using Integer.ParseInt():
Output:
Enter a binary number:
1010
Binary=1010 Decimal=10
Binary to Decimal using Integer.parseInt():
Output:
Enter a binary number:
1010
Result: 10
All your problems can be solved with a one-liner! To incorporate my solution into your project, simply remove your
binaryform(int number)
method, and replaceSystem.out.print(binaryform(number));
withSystem.out.println(Integer.toBinaryString(number));
.