0

I'm having trouble with this problem.

Here is the code I wrote out:

package com.jdewey.rvrs;
import java.util.Scanner;

public class Reverse {

    public static void main(String[] args) {
        Scanner console = new Scanner(System.in);
        System.out.print("Enter your string: ");
        String userIn = console.nextLine();
        int inLength = userIn.length();
        stringRvrs(userIn, inLength);

    }   
    public static void stringRvrs(String x, int length){
        for(int i = 1; i <= length; i++){
            int y = -1 * i + length;
            System.out.print(x.substring(y));;
        }
    }
}

It's supposed to output "tset" if you were to input "test"

Please help!

Raman Sahasi
  • 30,180
  • 9
  • 58
  • 71
Jon Dewey
  • 25
  • 6

3 Answers3

1

It makes more sense to just write your loop to start at the end of the string, and also to print each character using charAt instead of substring. See below:

public static void stringRvrs(String x, int length){
    String result = "";
    for(int i = length - 1; i >= 0; i--){
        result = result + x.charAt(i);
    }
    System.out.println(result);
}

Of course, there is an easier way using library functions to reverse a string (see here: Reverse a string in Java), but I assume this is a learning exercise for you so I corrected the code instead of just linking to an easy way to do it.

Community
  • 1
  • 1
nhouser9
  • 6,730
  • 3
  • 21
  • 42
1

Try StringBuilder as in:

public static void stringRvrs(String x){
        char [] all = x.toCharArray();
        StringBuilder concate = new StringBuilder();
        for(int i = all.length-1;i >= 0;i--){
            concate = concate.append(String.valueOf(all[i]));
        }
        System.out.println(x+" reversed to "+concate);
   }

No need to pass int length as an parameter to the method.

Young Emil
  • 2,220
  • 2
  • 26
  • 37
0

you can simply use stringBuilder.reverse();
your method should look like this after the changes,

public static void stringRvrs(String x, int length){
        StringBuilder sb = new StringBuilder(x);
         System.out.println(sb.reverse());
}


There is no need to pass the length of the String as an argument since it can be found using string.length(); at any point of time.

Adit A. Pillai
  • 647
  • 1
  • 10
  • 22