Home > front end >  Reverse String inside a While Loop
Reverse String inside a While Loop

Time:10-04

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

CodePudding user response:

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

CodePudding user response:

You can use one line to reverse the string

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