Reversing a Sentence with Java - No Loops

In summary, reversing a sentence with Java without using loops involves splitting the sentence into an array of words, creating a new string and adding the words in reverse order with a space in between, and finally printing out the reversed sentence. This method can be useful for tasks such as creating a user-friendly display of data or for implementing algorithms that require reversed input.
  • #1
J.live
95
0
We are asked to reverse a sentence , example: I am going. ==> .going am I

Attempt:

import java.util.Scanner;

public class Assign2
{
public static void main (String [] args)
{

String line= new StringBuffer().reverse().toString();
String line2 = new StringBuffer(line).reverse().toString();
Scanner keyboard = new Scanner (System.in);

System.out.println("Enter a line of text. No punctuation please. ");
line=keyboard.nextLine();


System.out.println( "I have rephrased that line to read ");
System.out.println( new StringBuffer(line).reverse().toString() );


}
}

Output:

Enter a line of text. No punctuation please.
Hello I am
I have rephrased that line to read
ma I olleH


Is there a way to do this problem without using loop?
Can someone give me a head start on how to do it using substrings?
Please, try to lay out some steps as I am trying to understand it. Thanks.
 
Technology news on Phys.org
  • #2
Added [ code] and [ /code] tags (without leading spaces) to your code, and indented it.
J.live said:
We are asked to reverse a sentence , example: I am going. ==> .going am I

Attempt:
Code:
import java.util.Scanner;

public class Assign2 
{
   public static void main (String [] args) 
   {

      String line= new StringBuffer().reverse().toString();
      String line2 = new StringBuffer(line).reverse().toString();
      Scanner keyboard = new Scanner (System.in);

      System.out.println("Enter a line of text. No punctuation please. ");
      line=keyboard.nextLine();


      System.out.println( "I have rephrased that line to read "); 
      System.out.println( new StringBuffer(line).reverse().toString() );
   }
}
Output:

Enter a line of text. No punctuation please.
Hello I am
I have rephrased that line to read
ma I olleH


Is there a way to do this problem without using loop?
Can someone give me a head start on how to do it using substrings?
Please, try to lay out some steps as I am trying to understand it. Thanks.
What do you mean "without using loop"? It looks like you did this without using a loop. Do you mean "using a loop"?

Using substrings, you would need to know how many spaces are in the entered string, since spaces are used to separate the individual words. Once you know how many spaces you could split the string at the spaces, and print the substrings backwards, with each one in reverse order.
 
  • #3
Well , what I did reversed the order of the letters along with the sentence. I just want the sentence to be reversed.

Sorry, I didn't quite get what you said there. Can you give me an example? Thanks.

I want to know, if I can reverse just the sentence not letters without the use of loop?
 
  • #4
I don't think you can do what you want without using a loop. If I understand you, for an input string of "Hello I am" you want to print "am I Hello". Is that right?

I haven't done any Java programming for about 16 years, and don't have a compiler for it installed, so I can't give you any examples. Take a look at the documentation for the String class, http://download.oracle.com/javase/1.5.0/docs/api/java/lang/String.html. Some methods that might be of use are indexOf, for finding where the space characters are located, and substring. Split might be useful, also.
 
  • #5
Can you not use an array and split the sentence at each " "?

In VB you can take a string: "Hello I Am" and use a split function to return three strings "Hello", "I" and "Am" and then assign them to an array.

So to get your sentence you'd just call your array back by index, in order.

To reverse it, you'd just call your array back in reverse index order (not forgetting to add spaces).
 
  • #6
Thank you , Mark and Jared.

Mark- Yes, that is correct. I have used substring . When I assign a substring a number value like in the given example ; it gives out an error. Yes, another person used a loop for my problem . Here is the code for that:

http://tinypic.com/view.php?pic=jai2dl&s=7But, I fail to understand the code from "words = line split (" ") ..." till the very end. Just does not make any sense to me. If any of you could explain it to me, ill appreciate it.

Jared- What If I scan the words from the keyboard? How do I reverse any typed in sentence using the same formula?
 
  • #7
What do you mean scan the words from the keyboard?

You assign the sentence to a string, you then scan it for all the instances of " " that occur in it. Assuming you have to declare the array length as with VB, the array length is then simply the count of spaces if zero based index, or number of spaces plus one if not.

That way, you can handle a sentence of any size.
 
  • #8
I meant , if the program prompts the user to input a sentence, will this way still work?

Can you give an example? I am not able to grasp what you are saying.
 
  • #9
J.live said:
I meant , if the program prompts the user to input a sentence, will this way still work?

My way? Certainly. I'm just not sure how to achieve it in Java.
Can you give an example? I am not able to grasp what you are saying.

For my system:
User inputs sentence.
Scan sentence for number of spaces.
Declare an array with an index equal to the number of spaces.
Use the split function to split the sentence using " " as the delimiter and assign it to the array.
You know have an array where the first item is the first word, the second item is the second word and so on.
So now, you know the size of the array so you compile a new string of the array values, starting with the last.
You now have a string written backwards.

I can do you a code example, but it would be in VB / VBA (can't remember where I used it last) and so I'm not sure if it would be any help to you.
 
  • #10
J.live said:
Mark- Yes, that is correct. I have used substring . When I assign a substring a number value like in the given example ; it gives out an error.
What error? We can't read your mind. What was the code that generated the error?
J.live said:
Yes, another person used a loop for my problem . Here is the code for that:

http://tinypic.com/view.php?pic=jai2dl&s=7


But, I fail to understand the code from "words = line split (" ") ..." till the very end. Just does not make any sense to me.
Then I suggest that you read up on for loops and arrays, since that's what the code there is using.
J.live said:
If any of you could explain it to me, ill appreciate it.
If you have specific questions, we're happy to help, but we're not going to write your code for you, which is what you seem to be asking for.
 
  • #11
I think you have misunderstood me. The code has already been written. That is not my concern. I want to understand what is going on in it. No, I am not too lazy to read up on it. I have read up on it. It's just the tone of the explanation in book is not in layman terms. Also, it takes time to gather all the info from the net.I can't devote all my time to one class.So, I thought it will be better if someone experienced can explain it in a simpler manner.

Sorry for not being specific, Mark.

Can you explain this line from the code:"for (i = words.length - 1; i >= 0 ; i--)"

what does the command above prompt the program to do?
What do "-1" , "i >=0" , "i --" refer to?

Thanks.
 
  • #12
Ah, I thought you needed the code. In which case, ignore my previous posts.
J.live said:
"for (i = words.length - 1; i >= 0 ; i--)"

I don't know java so I can't help you with this. I could attempt to explain based on how it looks, but I'd rather not as I could be way off.
 
  • #13
J.live said:
I think you have misunderstood me. The code has already been written. That is not my concern. I want to understand what is going on in it. No, I am not too lazy to read up on it. I have read up on it. It's just the tone of the explanation in book is not in layman terms. Also, it takes time to gather all the info from the net.I can't devote all my time to one class.So, I thought it will be better if someone experienced can explain it in a simpler manner.

Sorry for not being specific, Mark.

Can you explain this line from the code:


"for (i = words.length - 1; i >= 0 ; i--)"
This line is the header line of a for loop. The body of the for loop is the code between { and }.

There are three expressions in the parentheses above.
The first part is the initialization expression. Here it is i = words.length - 1. This assignment expression initializes the loop control variable i to the length of the words string, minus 1. For example, if the length of words happened to be 6, i would be set to 5. The initialization happens only once.

The second part is the test expression. Before each iteration is started, the current value of i is checked to see if it is >= 0. If so, the statements in the loop body are executed. If not, the loop exits.

The third part is the update expression. It usually increments or, in this case, decrements the loop control variable. This expression is evaluated after the last statement in the loop body executes. The expression i-- decrements (subtracts 1 from) the loop control variable. The real explanation is somewhat more complicated, but this is good enough for now.

Using the example where the words string is of length 6, here's what happens:
i = 5
i >= 0 is true
Loop body executes
i is decremented to 4

i >= 0 is true
Loop body executes
i is decremented to 3

i >= 0 is true
Loop body executes
i is decremented to 2

i >= 0 is true
Loop body executes
i is decremented to 1

i >= 0 is true
Loop body executes
i is decremented to 0

i >= 0 is true
Loop body executes
i is decremented to -1

i >= 0 is false
The next statement after the loop executes.

Notice that the loop executed 6 times, the same as the length of words.


J.live said:
what does the command above prompt the program to do?
What do "-1" , "i >=0" , "i --" refer to?

Thanks.
 
  • #14
J.live,
Sorry that I misunderstood you. Students occasionally post problems here at Physics Forums in hopes of getting someone here to do their work, which is a violation of rules of the forum.
 
  • #15
Thank you for an elaborate explanation. Starting to make some sense now.

Another question, if you don't mind.

Can you explain these lines as well:

lastchar= word.charAT (word.length ()-1);
if (!Character.isLetter(lastchar))
word=lastchar + word.substring(0, word.length ()-1);
reversed.append(word);
if (i>0) reversed.append (" ")

In this line: "lastchar= word.charAT (word.length ()-1);"
the charAT assigned lastchar to "i" right?

"if (!Character.isLetter(lastchar))"
Means, when and if it reaches the laschar then do the following?
So my question is what exactly is "!Character.isLetter"?

Lastly, what does this line do " word=lastchar + word.substring(0, word.length ()-1);"?
What does it mean by " lastchar +substring(0, word.length() -1)"?
What is the addition sign for? Also, what is "0" referring to?

Thanks.
 
  • #16
J.live said:
Thank you for an elaborate explanation. Starting to make some sense now.

Another question, if you don't mind.

Can you explain these lines as well:

lastchar= word.charAT (word.length ()-1);
if (!Character.isLetter(lastchar))
word=lastchar + word.substring(0, word.length ()-1);
reversed.append(word);
if (i>0) reversed.append (" ")

In this line: "lastchar= word.charAT (word.length ()-1);"
the charAT assigned lastchar to "i" right?
It's helpful to have a string in mind when looking at this code. Let's say that word in the code above is "tomorrow". The length of this string is 8, the 't' is at index 0, and the 'w' is at index 7.

word.length() evaluates to 8, so word.length() - 1 evaluates to 7.
charAt(7) is 'w', so the first line of code above sets lastchar to 'w'.

In the next line isLetter(lastchar) is true, since lastchar is 'w', so !Character.isLetter(lastchar) is false. There are several things going on here that deserve comment:
1) ! means NOT. It is the logical negation of whatever it operates on.
2) isLetter() is apparently a static method, so you call it with the name of the class rather than an instance of that class.

What this is really doing is saying that if the lastchar is not a letter then do what's in the body of the if statement.

On the other hand, if word was "tomorrow " (with a space at the end), then Character.isLetter(lastchar) would be false, and !Character.isLetter(lastchar) would be true, so the body of the if statement would be executed.

See if you can figure out what the next line of code is doing, namely
word=lastchar + word.substring(0, word.length ()-1);


J.live said:
"if (!Character.isLetter(lastchar))"
Means, when and if it reaches the laschar then do the following?
So my question is what exactly is "!Character.isLetter"?

Lastly, what does this line do " word=lastchar + word.substring(0, word.length ()-1);"?
What does it mean by " lastchar +substring"?

Thanks.
 
  • #17
That's doing it the hard way. Not a criticism in this case, because you learn a lot more doing it the way you've done it. However, I should point out that there's a much easier way:

Code:
public class WordReverser {

   public static void main(String[] args) {
      String[] result = "this is a test".split("\\s");
      for (int i = result.length-1; i >= 0; i--) {
         System.out.println(result[i]);
      }
   }
}

I'm not giving anything away here, I just reversed an example from the StringTokenizer class documentation (the class is obsolete now) which was pointing out one of the ways it can be done directly with the String class. So if you have to do something like splitting up a string in the future, you'll know a simple way to do it. It comes up from time to time.
 
  • #18
" word=lastchar + word.substring(0, word.length ()-1);"
Discards that last character that is not recognized by using the "word.length()-1 method?

I tried using the substring method to do the reversal, but it didn't work out.

Here is what I did:

public class Assign2
{
public static void main (String [] args)
{

String line, a;

Scanner keyboard = new Scanner (System.in);

System.out.println("Enter a line of text. No punctuation please. ");
line=keyboard.nextLine();
a= line.substring(7,0);

System.out.println( "I have rephrased that line to read ");
System.out.println(a );

}



}

Output:

Enter a line of text. No punctuation please.
Hello World

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -7
at java.lang.String.substring(String.java:1937)
at Assign2.main(Assign2.java:19)

It doesn't reverse it for me, rather pops an error.

P.S Thank you, Mark , for helping me out.Grep - Thanks. I tried that code you wrote. I have a question

How do you prompt the user to input a sentence with that exact same code? I tried but it didn't work.
 
Last edited:
  • #19
J.live said:
a= line.substring(7,0);

That won't work. You need to read the documentation on a function and understand it before trying to use it. It's plain in the documentation why that won't work, and what happens when you do that.

You can find some docs on the Java API here:

http://download.oracle.com/javase/6/docs/api/index.html

J.live said:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -7
at java.lang.String.substring(String.java:1937)
at Assign2.main(Assign2.java:19)

It doesn't reverse it for me, rather pops an error.
From the fine documentation for String.substring(int beginIndex, int endIndex):

Throws:
IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.

One last note: A string that is 10 characters long goes from index 0 to index 9. So if you want the index of the last character of a string 7 characters long, that index is 7-1 = 6. That might help with some of the trouble you're having.
 
  • #20
J.live said:
Grep - Thanks. I tried that code you wrote. I have a question

How do you prompt the user to input a sentence with that exact same code? I tried but it didn't work.
First, get it into a string. The line in question was:

String[] result = "this is a test".split("\\s");

So you can use your string instead of "this is a test". Let's say it's in a String called "line". Then it becomes something like:

String[] result = line.split("\\s");

It's that simple. I recommend you keep on trying to figure out the substring thing, however. Understanding it well should help with the rest of the course. Conversely, if you have trouble with it, I suspect you'll have even more trouble later on in the course. Figuring it out now will help you out later, and probably make the whole course more enjoyable and less frustrating. Don't worry, we're here to help! :smile:

EDIT: Oh yeah, and please wrap your code in code tags. It's so much easier to read. Removing the spaces from inside the square brackets, it's something like:
[ CODE ]
YOUR CODE GOES HERE
[ /CODE]
 
Last edited:
  • #21
Something like this:

Code:
import java.util.Scanner;public class WordReverser {
	
	public static void main(String[] args) {
 
        String line;
        String[] result = line.split("\\s");
         Scanner keyboard = new Scanner (System.in);
             for (int i = result.length-1; i >= 0; i--)
             line= keyboard.nextLine();
          System.out.print(result[i]);
  }

}

It is showing error at "System.out.print(result);" Underlining iI know, but I didn't have this much trouble with the first assignment.
Prof is of no help. He just reads off the book. Only people who are thriving in his class are people with good programming background. Most of us are behind.
 
Last edited:
  • #22
For your code tags, don't put any spaces inside the brackets. I took them out, and indented your code.
J.live said:
Something like this:
public static void main(String[] args) {

Code:
String line;
String[] result = line.split("\\s");
Scanner keyboard = new Scanner (System.in);
for (int i = result.length-1; i >= 0; i--)
   line= keyboard.nextLine();
System.out.print(result[i]);
It is showing error at "System.out.print(result);" Underlining i

In the first line of code, the variable line is uninitialized. That means that you can't come along in the second line and try to split it.
Things are going downhill from there.
J.live said:
I know, but I didn't have this much trouble with the first assignment.
Prof is of no help. He just reads off the book. Only people who are thriving in his class are people with good programming background. Most of us are behind.
 
  • #23
J.live said:
It is showing error at "System.out.print(result);" Underlining i

There's a few problems here. First, the line with "line.split"... What is it splitting? There's no string to split yet. You need to get it from the user first. So that "nextLine()" code is in the wrong place. Worse than that, it's in fact inside the for loop. Unless you use curly braces (i.e. { and }) around the code you want to repeat inside the for loop, the next line will be what gets repeated. So you're repeating the "nextLine()" line. What you wanted was for the System.out.print(result) line to be in the for loop.

The reason it's complaining is that there was nothing to split, and so nothing to print in that "result" array.

I personally suggest using curly braces in almost if not all cases.

There's a small issue with how you're using the String class, but I think we can ignore that for now.

J.live said:
I know, but I didn't have this much trouble with the first assignment.
Prof is of no help. He just reads off the book. Only people who are thriving in his class are people with good programming background. Most of us are behind.
Hm, I've seen that happen a few times. Well, at least you do have us. Mark knows what he's talking about, and is doing a good job at explaining, in my opinion. Make sure you understand everything he explained to you. I'm slightly regretting piping in at the point I did, because I didn't want to derail you from what Mark was walking you through.

One of the central skills for a programmer is to be able to go through things step by step. Maybe it would help if you worked this out on paper a bit?

For example:
1. Get one line of input from the user, and store in a String
2. etc...
 
  • #24
I think I am getting there. I finally got a correct output using substrings

Code:
import java.util.Scanner;

public class Assign2 
{
	public static void main (String [] args) 
  {
	
		
		
	
		String line, a,c;
		
		Scanner keyboard = new Scanner (System.in);

		System.out.println("Enter a line of text. No punctuation please. ");
		line=keyboard.nextLine();
		a= line.substring(5);
		c=line.substring(0,6);

		System.out.println( "I have rephrased that line to read "); 
		System.out.print(a);
		System.out.print( c );

Output:

Code:
Enter a line of text. No punctuation please. 
Hello World
I have rephrased that line to read 
 WorldHello

Can you guys explain how this ended up happening?

hello world => a has 5 characters 'h' is 0 right? 'w' is 5? Does substring (a) directly go to 5th letter 'w' and reads letters after it?

Yeah, thank you both of you. You guys have been great help.
 
Last edited:
  • #25
This is all way too complicated. (EDIT: Grep's way is nice too. I didn't notice it.) Use the sentence you want to reverse to initialize an instance of Scanner, and read Scanner.next() while it has a next.
Code:
String reverse(String sentence)
{
     Scanner s = new Scanner(sentence);
     String reversed = "";
     while(s.hasNext())
        reversed  = s.next() + " " + reversed;
     return reversed;
}

Remember, thinking is for real programming. This is Java. Always take the easy route.
 
Last edited:
  • #26
Given that you typed Hello World, that's what goes into line.
H is at index 0, the space is at index 5, W is at index 6, and d is at index 10.
a = line.substring(5) evaluates to the substring of line that starts at index 5, which is " World"
Note that there is a space at the beginning of the string.
c = line.substring(0, 6) evaluates to the subtring of line that starts at index 0 and ends at the character at index 6-1 , which is "Hello "
Note that there is a space at the end of the string.

Your output is
<sp>WorldHello<sp>
 
  • #27
It works now.

Code:
import java.util.Scanner;public class WordReverser {
	
	public static void main(String[] args) {
		
		 
	    
		String line, result[];
		 Scanner keyboard = new Scanner (System.in);
		 line=keyboard.nextLine();
		
		{
		 result = line.split("\\s");
		  for (int i = result.length-1; i >= 0; i--)
		  
			System.out.print(result[i]);

		}
	   }
  
}

Output:

Code:
hello how are you
youarehowhello

Question: what is "\\s"?

How do you space the output?
 
  • #28
"\\s" is the token at which Sting.split() splits the string into separate strings. The "\\s" is a regular expression that resolves to \s which tells split() to split the sting at every whitespace(space, tab, or return).

See http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#split%28java.lang.String%29 and http://download.oracle.com/javase/1.4.2/docs/api/java/util/regex/Pattern.html#sum for more info.
 
Last edited by a moderator:
  • #29
J.live said:
Question: what is "\\s"?

How do you space the output?
It's a regular expression. I won't get into them now. They get complicated, but in this case it's not too complicated. \s means a whitespace character (space, tab, newline are the important ones). Only problem is, backslash is a special character (like using \n to mean a newline character). So if you want to have a real, actual backslash in a string, you need to use \\ rather than just one backslash.

For example, it comes up in Windows programming where the backslash is used for paths. So if you have a file called "C:\directory\file.txt", if you want to put that in a string to, say, open that file and so something to it, you need to do this: "C:\\directory\\file.txt". The \\ become just a single \ in the actual string.

Hope that was clear. In short, if you want a backslash character in a string, use \\ and not just \.

Just a note on your code. The curly braces aren't quite in the right place. Remove that one above the split line, and make the for loop look like this:
Code:
for (int i = result.length-1; i >= 0; i--) {
    System.out.print(result[i]);
}

I put the opening curly brace on the same line as the for loop because that's part of the Java formatting standard everyone uses. But it's probably clearer to put it on the next line like this (less chance of not noticing it):
Code:
for (int i = result.length-1; i >= 0; i--)
{
    System.out.print(result[i]);
}

Your choice which you like better, really, unless you're told otherwise.

EDIT: Almost forgot. An easy way to add a space between the words is just to append a space to each word when you print it. You can do it like this:

System.out.print(result + " ");

It does print a space after the last word, which isn't needed, but it matters little. You could also just do a 'System.out.print(" ")' after printing the word and only if you're not on the last word.
 
  • #30
Oh nice, got it. Thanks a lot Grep. I need to read up and practice what you have mentioned. I appreciate your help.

Thanks to Tyler as well for the help.
 
Last edited:
  • #31
"\n" is a control character, whereas "\\s" is a regular expression. They are two separate things.

what about spacing out "youarehowhello"? Do I use "\\s" to split that?
You can't. You have to put the spaces in while you are combining them into one string, or use the method I just posted.
 
  • #32
J.live said:
Oh nice, got it. Thanks a lot Grep. I need to read up and practice what you have mentioned. I appreciate your help.
No problem. And you might want to make sure you look at TylerH's solution as well, just to understand it. It's probably the simplest way of all. Just go through the words in order, and keep adding each word to the start of some output string. Voila, reversed words. Simple and clear are winners in my book.

I have to admit, parsing strings "the hard way" might teach you more, but may be a little much to ask of you at this point.

Oh, and you might want to make sure everything is indented properly before submitting. It's a little off. And remove any extra blank lines that aren't needed. Keep ones that help make things clear and that separate groups of lines that belong together. It'll make it look nicer.
 
  • #33
This is how I would format your code.
EDIT: Add missing final brace.
Code:
import java.util.Scanner;


public class WordReverser
{
	
   public static void main(String[] args) 
   {
      String line, result[];
      Scanner keyboard = new Scanner (System.in);
      line=keyboard.nextLine();
		
      result = line.split("\\s");
      for (int i = result.length-1; i >= 0; i--)
      {
         System.out.print(result[i]);
      }
  }
}
 
Last edited:
  • #34
Mark44 said:
This is how I would format your code.
Except I'm guessing you wouldn't normally be missing a closing curly brace to close the function. :wink:

So you normally use 3 space indenting? You'd be one of the only people I've ever met that does that other than myself. I learned it when I was writing safety critical software where every little thing was scrutinized, and proper indentation (and thus clarity) was very important. I do it because it makes it obvious when someone has used tab characters for indenting since pretty much nobody has their tab stops set to 3. Same reason for you? Just curious.
 
  • #35
I prefer tabs to spaces because any good editor or IDE let's the user adjust tab length. Or... do you mean that you have you tab length set to 3?
 

Similar threads

  • Programming and Computer Science
Replies
8
Views
1K
  • Programming and Computer Science
Replies
8
Views
1K
  • Programming and Computer Science
Replies
2
Views
1K
  • Programming and Computer Science
Replies
3
Views
765
  • Programming and Computer Science
Replies
1
Views
6K
  • Programming and Computer Science
Replies
1
Views
6K
  • Programming and Computer Science
Replies
14
Views
3K
  • Programming and Computer Science
Replies
1
Views
7K
  • Programming and Computer Science
Replies
2
Views
1K
  • Programming and Computer Science
Replies
2
Views
2K
Back
Top