Java- reverse sentence

  • Java
  • Thread starter J.live
  • Start date
  • #1
95
0

Main Question or Discussion Point

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.
 

Answers and Replies

  • #2
33,513
5,195
Added [ code] and [ /code] tags (without leading spaces) to your code, and indented it.
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
95
0
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
33,513
5,195
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
2,685
20
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
95
0
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=7


But, 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
2,685
20
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
95
0
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
2,685
20
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
33,513
5,195
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?
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.
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
95
0
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
2,685
20
Ah, I thought you needed the code. In which case, ignore my previous posts.
"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
33,513
5,195
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.


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

Thanks.
 
  • #14
33,513
5,195
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
95
0
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
33,513
5,195
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);


"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
297
2
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
95
0
" 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
297
2
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

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
297
2
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
95
0
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 i


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.
 
Last edited:
  • #22
33,513
5,195
For your code tags, don't put any spaces inside the brackets. I took them out, and indented your code.
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.
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
297
2
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.

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
95
0
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
724
0
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:

Related Threads on Java- reverse sentence

Replies
3
Views
2K
Replies
2
Views
10K
  • Last Post
Replies
9
Views
2K
  • Last Post
Replies
4
Views
2K
  • Last Post
Replies
2
Views
2K
  • Last Post
Replies
2
Views
1K
  • Last Post
Replies
4
Views
952
  • Last Post
Replies
2
Views
1K
  • Last Post
Replies
3
Views
2K
  • Last Post
Replies
1
Views
3K
Top