I just started learning Java and I'm doing a little program to convert a decimal number into binary numbers using only while loops.
The results were reversed, therefore I'm using a method to reverse the string. But the reverse method does not work for me. Could anyone help me, please?
The following is my code:
import java.util.Scanner;
public class NumberConversion {
public static void main(String[] args) {
Scanner getnumber = new Scanner(System.in);
System.out.print("Enter number: ");
int originalnum = getnumber.nextInt();
int remainder;
String binary_temp;
if (originalnum % 2 != 0) {
while (originalnum > 0) {
remainder = originalnum % 2;
originalnum /= 2;
binary_temp = String.valueOf(remainder);
String binarynum = new StringBuffer(binary_temp).reverse().toString();
System.out.print(binarynum);
}
}
else if (originalnum % 2 == 0) {
while (originalnum > 0) {
originalnum /= 2;
remainder = originalnum % 2;
binary_temp = String.valueOf(remainder);
String binarynum = new StringBuffer(binary_temp).reverse().toString();
System.out.print(binarynum);
}
}
}
}
That's because you are reversing a string that contains a single digit. If you run your code through a debugger, you will discover that. Every programmer needs to know how to debug code, including code written by other people.
You need to build up the string of binary digits using a single
StringBufferand only after thewhileloop you reverse the string.Also, from the code in your question:
If the above condition is not true, then
originalnum % 2must be zero, hence not need forif-else, i.e. (also from the code in your question):You just need
elseby itself.However, you don't need that
if-elseat all. You just need a singlewhileloop and a singleStringBuffer. Actually, for a single-threaded program – such as yours – it is better to use StringBuilder. And rather than creating a newStringBufferand reversing it on each iteration of thewhileloop, you can simply insert the [binary] digit.(More notes after the code.)
abs.whileloop does not handle the case whereoriginalnumis 0 (zero), hence theif (originalnum == 0)Have you seen Oracle's Java tutorials?
I also recommend the book Java by Comparison by Simon Harrer, Jörg Lenhard & Linus Dietz.