Reverse String inside a While Loop

219 Views Asked by At

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);
            }
        }
    }
}
3

There are 3 best solutions below

0
Abra On BEST ANSWER

But the reverse method does not work for me.

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 StringBuffer and only after the while loop you reverse the string.

Also, from the code in your question:

if (originalnum % 2 != 0) {

If the above condition is not true, then originalnum % 2 must be zero, hence not need for if-else, i.e. (also from the code in your question):

else if (originalnum % 2 == 0) {

You just need else by itself.

However, you don't need that if-else at all. You just need a single while loop and a single StringBuffer. Actually, for a single-threaded program – such as yours – it is better to use StringBuilder. And rather than creating a new StringBuffer and reversing it on each iteration of the while loop, you can simply insert the [binary] digit.

(More notes after the 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();
        originalnum = Math.abs(originalnum);
        StringBuilder sb = new StringBuilder();
        if (originalnum == 0) {
            sb.append('0');
        }
        else {
            while (originalnum > 0) {
                int remainder = originalnum % 2;
                sb.insert(0, remainder);
                originalnum /= 2;
            }
        }
        System.out.println(sb);
    }
}
  • I assume that you only want to handle positive numbers, hence the call to method abs.
  • The while loop does not handle the case where originalnum is 0 (zero), hence the if (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.

1
Amit Rai On

you can use for loop and server your string , here is example

public class StringFormatter {  
public static String reverseString(String str){  
    char ch[]=str.toCharArray();  
    String rev="";  
    for(int i=ch.length-1;i>=0;i--){  
        rev+=ch[i];  
    }  
    return rev;  
}  
} 
0
Prateek Gaur On

You can use one line to reverse the string

String reversedString = (new StringBuilder().append(oldString).reverse().toString());