I made a program that converts a decimal number given from the user, and converts it to a binary number. For example, if I entered 2, it would return 10. It then, counts the amount of ones and zeros in the binary conversion. Please tell me any way my code can be either, more efficient, or if there is an error with my code. If there are any bad practices used, please tell me. Indentation is also important to me.
package Conversions;
import java.util.Scanner;
public class BinaryChallenge {
@SuppressWarnings("resource")
public static void main(String[] args) {
int number;
Scanner scan = new Scanner(System.in);
int oneCount = 0;
int zeroCount = 0;
System.out.println("Enter a positive integer");
number = scan.nextInt();
String binary = "";
if (number < 0) {
System.out.println("Error: Not a positive integer");
} else {
while(number > 0) {
int mod = (number % 2);
number /= 2;
binary = Integer.toString(mod) + binary;
}
System.out.println("The binary representation of your integer is: " + binary + ".");
}
for (int i = 0; i < binary.length(); i++) {
if (binary.charAt(i) == '1') {
oneCount++;
} else if(binary.charAt(i) == '0') {
zeroCount++;
}
}
System.out.println("The binary representation of your integer has: " + oneCount + " ones.");
System.out.println("The binary representation of your integer has: " + zeroCount + " zeros.");
System.out.println("The binary representation of your integer has 0 twos... duh.");
}
}