Home > database >  Program to reverse a string; program not t=returning reversed string
Program to reverse a string; program not t=returning reversed string

Time:01-22

I want to know what is going wrong with the below program as it is not returning reversed string.

public class Main {
    String reverse(String str){
        String rev="";
        char ch[]= str.toCharArray();
      
        for(int i=ch.length-1; i>=0; i--){
           
            rev = rev ch[i];
            
        }
        return rev;
    }
    
    public static void main(String[] args) {
       Main obj = new Main();
        obj.reverse("saumya");
    }
}

CodePudding user response:

You forgot to print the returned string


public class Main {
    String reverse(String str){
        String rev="";
        char ch[]= str.toCharArray();
      
        for(int i=ch.length-1; i>=0; i--){
           
            rev = rev ch[i];
            
        }
        return rev;
    }
    
    public static void main(String[] args) {
       Main obj = new Main();
       System.out.println(obj.reverse("saumya"));
    }
}

I got this output

aymuas

CodePudding user response:

There is nothing wrong with your code. Since you are not printing anything to the console, you are not getting anything on the output.You forgot to store the string that is returned by the reverse function. Just add it and it gives correct output.

public class Main {
    String reverse(String str){
        String rev="";
        char ch[]= str.toCharArray();
      
        for(int i=ch.length-1; i>=0; i--){
           
            rev = rev ch[i];
            
        }
        return rev;
    }
    
    public static void main(String[] args) {
       Main obj = new Main();
        String res = obj.reverse("saumya");
        System.out.println(res);
    }
}

and it gives the output

aymuas
  •  Tags:  
  • Related