Programmers learn & share
0 votes
52 views

Problem :

I am trying to print every string in Reverse Double Character way (e.g. string -> ggnniirrttss)

import java.util.Scanner;
public class ReverseDoubleCharecters {
public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.println("Enter a string to be reversed");
    String str = input.nextLine();
    String new_str = "";
    String result = "";
    for (int j = 0; j < str.length(); i++) {
        result += str.substring(i, j + 1) + str.substring(j, j + 1);
        String result2 = null;
        result2 = result;
        System.out.println(result2);
        }
    }
}

Still when I execute this code all I get as follows:

ss
tt
rr
ii
nn
gg

All double characters are printed on new lines. Anybody has the solution on this?

by (6.9k points)   | 52 views

1 Answer

0 votes

Solution :

Please have a look at the comments on the lines which I have updated:

1.      Please Iterate the string in backward way

2.      Do not try to print each double char in each loop iteration since you are need to print only the final result

3.      So Print the final result only after the loop

import java.util.Scanner;

public class ReverseDoubleCharecters {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.println("Enter a string to be reversed ");

String str = input.nextLine();

String new_str = "";

String result = "";

for (int j = str.length() - 1; j >= 0;j--) { // Please Iterate the string in backward way

 result += str.substring(j, j + 1) + str.substring(j j + 1); //Concatenate

String result2 = null;

 result2 = result;

// System.out.println(result2); // Do not try to print each double char in each loop iteration since you are need to print only the final result

}

System.out.println(result); // So Print the final result only after the loop

}

}

Output:

Enter a string to be reversed  string

ggnniirrttss

by (36.1k points)  
2,245 questions
2,807 answers
60 comments
241 users