Java - reverse sentences using Stacks - java

I am attempting to create a method that accepts a string as an input and returns another string that reverses the order of each sentence in the input using Stacks. For example, if the user inputs "hi there. i like red." the outputted string should be "there hi. red like i.". The following program I have created works fine for only one sentence. How could i modify the method to recognize a period, and start the method over again? Currently, if I input "hi there", the output is "there hi", which is just fine. However, if I input "hi there. i like red.", the output is "red. like i there. hi". How can I modify this reverseSentence method to recognize periods and to start over for the next sentence? Any advise or tips will be very helpful.
//Reverses the order of words inside of sentences.
import java.util.*;
import java.util.regex.*;
public class reverse {
//reverses the string using a stack
private static String reverseSentence(String inputString) {
String[] arrString = inputString.trim().split(Pattern.quote(" "));
Stack stack = new Stack();
for(String word : arrString)
{
stack.push(word);
}
StringBuilder builder = new StringBuilder();
while( !stack.isEmpty())
{
builder.append(stack.pop()).append(" ");
}
return builder.toString();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Stack<String> stack = new Stack<String>();
System.out.printf("Enter a sentence: ");
String sentence = scanner.nextLine();
if (sentence == null || sentence.length() == 0) {
System.out.println("Invalid...");
return;
}
String reverse = reverseSentence(sentence);
System.out.printf("Reversed string using stack is : %s", reverse);
while (!stack.isEmpty()) {
System.out.print(stack.pop() + " ");
}
}
}

Before splitting the input at the space, trim it by period and run the logic inside your method in a for-loop for every sentence / splitted part you got earlier.
In your main-method, instead of calling reverseSentence:
String[] sentences = sentence.trim().split(Pattern.quote("."));
for (String toReverse : sentences) {
System.out.print(reverseSentece(toReverse));
}
I know this is not perfect, but I hope to give an idea of what I mean, because I am typing on my phone.

There are two approaches that come to my mind to achieve this:
First split the string by '.', giving you a list of sentences in the string. Apply your logic to every sentence. Output every reversed sentence separated by a period.
Use your current logic, but before adding any word to stack, check if the word's last character is a period. If it is, this means it is the end of a sentence. Pop the stack till empty and display contents. (This will display the inverted sentence till here) Continue with the next word.
Hope this helps!

Use the string split method.
String[] sentences = sentence.split ("\\."); maybe?

Related

How do i print the the first initial of a string and the last word of a string?

How do I print only the first letter of the first word and the whole word of the last? for example,
I will request username input like "Enter your first and last name" and then if I type my name like "Peter Griffin", I want to print only "P and Griffin". I hope this question make sense. Please, help. I'm a complete beginner as you can tell.
Here is my code:
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
System.out.println("Enter your first and last name");
String fname=scan.next();
}
The String methods trim, substring, indexof, lastindexof, and maybe split should get you going.
This should do the work (typed directly here, so syntax errors might be there)
String fname=scan.nextLine(); // or however you would read whole line
String parts=fname.split(" ");
System.out.printf("%s %s",parts[0].substring(0,1),parts[parts.length-1]);
What you have to do next:
Check if there actually at least 2 elements in parts array
Check if first element is actually at least 1 char (no empty parts)
Check if there is actually line to read
Do your next homework yourself, otherwise you will not anything
I recommand you to watch subString(1, x) and indexOf(" ") to cut from index 1 to first space.
or here a other exemple, dealing with lower and multi name :
String s = "peter griffin foobar";
String[] splitted = s.toLowerCase().split(" ");
StringBuilder results = new StringBuilder();
results.append(String.valueOf(splitted[0].charAt(0)).toUpperCase() + " ");
for (int i = 1; i < splitted.length; i++) {
results.append(splitted[i].substring(0, 1).toUpperCase() + splitted[i].substring(1)+" ");
}
System.out.println(results.toString());

Am I overcomplicating a simple solution in Java?

For my Java homework I need to create a script that returns the first word within a string, and, as a part two, I need to also return the second word. I'm currently working on the first part, and I think I'm close, but I'm also wondering if I am over complicating my code a bit.
public static void statements(){
Scanner userInput = new Scanner(System.in);
char [] sentenceArray;
String userSentence;
char sentenceResult;
System.out.print("Enter a complete sentence: ");
userSentence = userInput.nextLine();
for(int x = 0; x < userSentence.length(); x++){
sentenceResult = userSentence.charAt(x);
sentenceArray = new char[userSentence.length()];
sentenceArray[x] = sentenceResult;
if(sentenceArray[x] != ' '){
System.out.print(sentenceArray[x]);
//break; This stops the code at the first letter due to != ' '
}
}
}
I think I've nearly got it. All I need to get working, for the moment, is the for loop to exit once it recognizes there is a space, but it prints out the entire message regardless. I'm just curious if this can be done a little simpler, as well as maybe a hint of what I could do instead, or how to finish.
Edit: I was able to get the assignment completed by using the split method. This is what it now looks like
public static void statements(){
Scanner userInput = new Scanner(System.in);
String userSentence;
System.out.print("Enter a complete sentence: ");
userSentence = userInput.nextLine();
String [] sentenceArray = userSentence.split(" ");
System.out.println(sentenceArray[0]);
System.out.println(sentenceArray[1]);
}
}
As it is your homework, I would feel bad to give you code and resolve it for you.
Seems like you really overcomplicated that, and you are aware, so it's good sign.
I need to create a script that returns the first word within a string,
and, as a part two, I need to also return the second word
So, you have a String object, then check yourself the methods of that class.
It is possible to solve it in 2 lines of code, but:
you must be aware of one special method of String class, the most useful will be one that could somehow split the string for you
you need to have some knowledge about java regular expressions - words are separated by space
after you split the string, you should get an array, accessing first and second element by index of an array will be sufficient
Personally, I think you are overthinking it. Why not read in the whole line and split the string by whitespaces? This isn't a complete solution, just a suggestion for how you can get the words.
public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a complete sentence: ");
try {
String userSentence = reader.readLine();
String[] words = userSentence.split(" ");
System.out.println(words[0]);
System.out.println(words[1]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Here's how I'd do it. Why not return all the words?
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Add something descriptive here.
* User: MDUFFY
* Date: 8/31/2017
* Time: 4:58 PM
* #link https://stackoverflow.com/questions/45989774/am-i-over-complicating-a-simple-solution
*/
public class WordSplitter {
public static void main(String[] args) {
for (String arg : args) {
System.out.println(String.format("Sentence: %s", arg));
List<String> words = getWords(arg);
System.out.println(String.format("# words : %d", words.size()));
System.out.println(String.format("words : %s", words));
}
}
public static List<String> getWords(String sentence) {
List<String> words = new ArrayList<>();
if ((sentence != null) && !"".equalsIgnoreCase(sentence.trim())) {
sentence = sentence.replaceAll("[.!?\\-,]", "");
String [] tokens = sentence.split("\\s+");
words = Arrays.asList(tokens);
}
return words;
}
}
When I run it with this input on the command line:
"The quick, agile, beautiful fox jumped over the lazy, fat, slow dog!"
Here's the result I get:
Sentence: The quick, agile, beautiful fox jumped over the lazy, fat, slow dog!
# words : 12
words : [The, quick, agile, beautiful, fox, jumped, over, the, lazy, fat, slow, dog]
Process finished with exit code 0

Two problems, using charAt for undefined input and looping output

So, I posted this nearly identical code yesterday, asking about how to leave the punctuation at the end of a reversed sentence after using .split. I'm still struggling with it, but I'm also having another issue with the same code: And here is my screen shot http://i.stack.imgur.com/peiEA.png
import java.util.Scanner;
import java.util.StringTokenizer; // for splitting
public class MyTokenTester
{
public static void main(String\[\] args)
{
Scanner enter = new Scanner(System.in);
String sentinel = ""; // condition for do...while
String backward = ""; // empty string
char lastChar = '\0';
do
{
System.out.println("Please enter a sentence: ");
String sentence = enter.nextLine();
String\[\] words = sentence.split(" "); // array words gets tokens
// System.out.printf("The string is%s",sentence.substring(sentence.length()));
for (int count = words.length -1; count>=0; count--) // reverse the order and assign backward each token
{
backward += words\[count\] + " ";
}
System.out.println(backward); // print original sentence in reverse order
System.out.println("Hit any key to continue or type 'quit' to stop now: ");
sentinel = enter.nextLine();
sentinel = sentinel.toLowerCase(); // regardless of case
} while (!sentinel.equals("quit")); // while the sentinel value does not equal quit, continue loop
System.out.println("Programmed by ----");
} // end main
} // end class MyTokenTester][1]][1]
As you guys can probably see my from screen shot, when the user is prompted to add another sentence in, the previous sentence is read back again.
My questions are:
How do I use charAt to identify a character at an undefined index (user input with varying lengths)
How do I stop my sentence from reading back after the user decides to continue.
Again, as I said, I'd posted this code yesterday, but the thread died and I had additional issues which weren't mentioned in the original post.
To address part 2, if you want to stop the sentence from reading back previous input, then reset backward to an empty string, because as it stands now, you're constantly adding new words to the variable. So to fix this, add this line of code right before the end of your do-while loop,
backward = "";
To address part 1, if you want to check the last character in a string, then first you have to know what is the last index of this string. Well, a string has indexes from 0 to str.length()-1. So if you want to access the very last character in the user input, simply access the last word in your words array (indexed from 0 to words.length - 1) by doing the following,
words[count].charAt(words[count].length() - 1);
Note that count is simply words.length - 1 so this can be changed to your liking.
1) So you have this array of strings words. Before adding each word to the backward string, you can use something like: words[count].chartAt(words[count].length() - 1). It will return you the charater at the last position of this word. Now you are able to do you checking to know wether it is a letter or any special char.
2) The problem is not that it is reading the previous line again, the problem is that the backward string still has the previous result. As you are using a + operator to set the values of the string, it will keep adding it together with the previous result. You should clean it before processing the other input to have the result that you want.
here is your code:
import java.util.*;
public class main{
public static void main(String[] args){
Scanner enter = new Scanner(System.in);
String sentinel = ""; // condition for do...while
String backward = ""; // empty string
char lastChar = '\0';
do
{
System.out.println("Please enter a sentence: ");
String sentence = enter.nextLine();
String[] words = sentence.split(" "); // array words gets tokens
// System.out.printf("The string is%s",sentence.substring(sentence.length()));
List<String> items = Arrays.asList(words);
Collections.reverse(items);
System.out.println(generateBackWardResult(items)); // print original sentence in reverse order
System.out.println("Hit any key to continue or type 'quit' to stop now: ");
sentinel = enter.nextLine();
// i use quals ignore case, makes the code more readable
} while (!sentinel.equalsIgnoreCase("quit")); // while the sentinel value does not equal quit, continue loop
System.out.println("Programmed by ----");
} // end main
static String generateBackWardResult(List<String> input){
String result="";
for (String word:input){
result =result +" "+word;
}
return result;
}
} // end class MyTokenTester][1]][1]
there are also some thing to mention:
* never invent the wheel again! (for reverting an array there are lots of approaches in java util packages, use them.)
*write clean code, do each functionality, i a separate method. in your case you are doing the reverting and showing the result in a single method.

print even words from string input?

I am in a beginners course but am having difficulty with the approach for the following question: Write a program that asks the user to enter a line of input. The program should then display a line containing only the even numbered words.
For example, if the user entered
I had a dream that Jake ate a blue frog,
The output should be
had dream Jake a frog
I am not sure what method to use to solve this. I began with the following, but I know that will simply return the entire input:
import java.util.Scanner;
public class HW2Q1
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a sentence");
String sentence = keyboard.next();
System.out.println();
System.out.println(sentence);
}
}
I dont want to give away the answer to the question (for the test, not here), but I suggest you look into
String.Split()
From there you would need to iterate through the results and combine in another string for output. Hope that helps.
While there will be more simpler and easier way to do this, I'll use the basic structure- for loop, if block and a while loop to achieve it. I hope you will be able to crack the code. Try running it and let me know if there is an error.
String newsent;
int i;
//declare these 2 variables
sentence.trim(); //this is important as our program runs on space
for(i=0;i<sentence.length;i++) //to skip the odd words
{
if(sentence.charAt(i)=" " && sentence.charAt(i+1)!=" ") //enters when a space is encountered after every odd word
{
i++;
while(i<sentence.length && sentence.charAt(i)!=" ") //adds the even word to the string newsent letter by letter unless a space is encountered
{
newsent=newsent + sentence.charAt(i);
i++;
}
newsent=newsent+" "; //add space at the end of even word added to the newsent
}
}
System.out.println(newsent.trim());
// removes the extra space at the end and prints newsent
you should use sentence.split(regex) the regular expression is going to describe what separate your worlds , in your case it is white space (' ') so the regex is going to be like this:
regex="[ ]+";
the [ ] means that a space will separate your words the + means that it can be a single or multiple successive white space (ie one space or more)
your code might look like this
Scanner sc= new Scanner(System.in);
String line=sc.nextLine();
String[] chunks=line.split("[ ]+");
String finalresult="";
int l=chunks.length/2;
for(int i=0;i<=l;i++){
finalresult+=chunks[i*2]+" ";//means finalresult= finalresult+chunks[i*2]+" "
}
System.out.println(finalresult);
Since you said you are a beginner, I'm going to try and use simple methods.
You could use the indexOf() method to find the indices of spaces. Then, using a while loop for the length of the sentence, go through the sentence adding every even word. To determine an even word, create an integer and add 1 to it for every iteration of the while loop. Use (integer you made)%2==0 to determine whether you are on an even or odd iteration. Concatenate the word on every even iteration (using an if statement).
If you get something like Index out of range -1, manipulate the input string by adding a space to the end.
Remember to structure the loop such that, regardless of the whether it is an even or odd iteration, the counter increases by 1.
You could alternatively remove the odd words instead of concatenation the even words, but that would be more difficult.
Not sure how you want to handle things like multiple spaces between words or weird non-alphabetically characters in the entry but this should take care of the main use case:
import java.util.Scanner;
public class HW2Q1 {
public static void main(String[] args)
{
System.out.println("Enter a sentence");
// get input and convert it to a list
Scanner keyboard = new Scanner(System.in);
String sentence = keyboard.nextLine();
String[] sentenceList = sentence.split(" ");
// iterate through the list and write elements with odd indices to a String
String returnVal = new String();
for (int i = 1; i < sentenceList.length; i+=2) {
returnVal += sentenceList[i] + " ";
}
// print the string to the console, and remove trailing whitespace.
System.out.println(returnVal.trim());
}
}

How to show sentence word by word in a separate line

The sentence String is expected to be a bunch of words separated by spaces, e.g. “Now is the time”.
showWords job is to output the words of the sentence one per line.
It is my homework, and I am trying, as you can see from the code below. I can not figure out how to and which loop to use to output word by word... please help.
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the sentence");
String sentence = in.nextLine();
showWords(sentence);
}
public static void showWords(String sentence) {
int space = sentence.indexOf(" ");
sentence = sentence.substring(0,space) + "\n" + sentence.substring(space+1);
System.out.println(sentence);
}
}
You're on the right path. Your showWords method works for the first word, you just have to have it done until there are no words.
Loop through them, preferably with a while loop. If you use the while loop, think about when you need it to stop, which would be when there are no more words.
To do this, you can either keep an index of the last word and search from there(until there are no more), or delete the last word until the sentence string is empty.
Since this is a homework question, I will not give you the exact code but I want you to look at the method split in the String-class. And then I would recommend a for-loop.
Another alternative is to replace in your String until there are no more spaces left (this can be done both with a loop and without a loop, depending on how you do it)
Using regex you could use a one-liner:
System.out.println(sentence.replaceAll("\\s+", "\n"));
with the added benefit that multiple spaces won't leave blank lines as output.
If you need a simpler String methods approach you could use split() as
String[] split = sentence.split(" ");
StringBuilder sb = new StringBuilder();
for (String word : split) {
if (word.length() > 0) { // eliminate blank lines
sb.append(word).append("\n");
}
}
System.out.println(sb);
If you need an even more bare bones approach (down to String indexes) and more on the lines of your own code; you would need to wrap your code inside a loop and tweak it a bit.
int space, word = 0;
StringBuilder sb = new StringBuilder();
while ((space = sentence.indexOf(" ", word)) != -1) {
if (space != word) { // eliminate consecutive spaces
sb.append(sentence.substring(word, space)).append("\n");
}
word = space + 1;
}
// append the last word
sb.append(sentence.substring(word));
System.out.println(sb);
Java's String class has a replace method which you should look into. That'll make this homework pretty easy.
String.replace
Update
Use the split method of the String class to split the input string on the space character delimiter so you end up with a String array of words.
Then loop through that array using a modified for loop to print each item of the array.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the sentence");
String sentence = in.nextLine();
showWords(sentence);
}
public static void showWords(String sentence) {
String[] words = sentence.split(' ');
for(String word : words) {
System.out.println(word);
}
}
}

Categories

Resources