36.0k views
5 votes
I need this code to print in reverse without spaces. please help....

example:
input: dog is pretty
output: ytterpsigod


import java.util.Scanner;

// Class
class Main {

// Main driver method
public static void main(String[] args)
{

Scanner input = new Scanner(System.in);
System.out.print("input the string sentence: ");
String words = input.nextLine();

String callM = reverseFor(words);

System.out.println(callM);



}


public static String reverseFor (String str2)
{


String reversedString = "";
String count = "";
for (int i = str2.length()-1; i>=0; --i) {
reversedString = reversedString + str2.charAt(i);
if (!Character.isWhitespace(reversedString))
{
count = count + reversedString;

}
}

return reversedString;
}
}

User Jakevdp
by
8.4k points

1 Answer

0 votes
Certainly! I see that you want to modify the provided code to print the reversed string without spaces. Here’s an updated version of the code that achieves that:

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the string sentence: ");
String words = input.nextLine();

String reversedString = reverseWithoutSpaces(words);
System.out.println(reversedString);
}

public static String reverseWithoutSpaces(String str) {
String reversedString = "";
for (int i = str.length() - 1; i >= 0; i--) {
if (!Character.isWhitespace(str.charAt(i))) {
reversedString += str.charAt(i);
}
}
return reversedString;
}
}

With this updated code, the reverseWithoutSpaces method iterates over the characters of the input string in reverse order and appends non-space characters to the reversedString. Finally, the reversed string without spaces is returned and printed.
User Shammara
by
7.8k points