push() etc in an ArrayStack - java

For my assignment I've had to create an ArrayStack, a StackADT, and now I have to make a program to take in a string and output it in reverse.
Now this sounds simple, but I have no idea how to push something into the array. I've been googling the shit out of this and can't find an actual answer that makes sense.
Specifically I'm having trouble linking the main program to the actual array, and then linking the input string to the push().
public class ReverseSentenceMain {
public static void main (String[] args)
{
AssignmentArrayStack stack = new AssignmentArrayStack();
//private AssignmentArrayStack<String> stack;
public ReverseSentenceMain()
{
stack = new AssignmentArrayStack<Integer>();
}
String sentence;
String result = null;
String words;
stack = (T[])(new Object[initialCapacity]);
Scanner in = new Scanner(System.in);
System.out.println("Enter a sentence");
}
}
I'd appreciate any help and thanks for your time

You start scanning by calling next on the scanner.
sentence = in.next();
Then you perform a split on whitespace to divide up the sentence into tokens that you push into your stack. The scanner can do the split for you I think. Look at the Scanner JavaDoc or String JavaDoc for more information.

You should format the code. Press ctrl+K or use the little 101010 icon.
Anyways. The stack class should have a push method. You need to get the sentence. You could loop through the sentence and then push the characters onto a stack. Once you do that, then you can pop the characters off to print the string in reverse order.
loop through string
stack.push(string[i])
while(currChar = stack.pop())
print currChar (or store to another variable)
I believe that will work. Been a while since ive done anything in java.
A stack isn't really an array. Its more like a linked list. It adds an element as the first element in a linked list and then updates the pointer.
Acutally heres a decent example http://www.javacoffeebreak.com/faq/faq0037.html
And i just noticed you want to reverse the sentence and not the word, so do what willcodejavaforfood said and tokenize it with scanner. I remember you can do this. It will read up every whitespace. you get that token and add it to the stack. Some kind of type of concept though.

Related

Need help reading through my String to push to Stack

Hello and thank you for reading. I have written a program to reverse the words in a string using a stack. I am to use 3 sentences and reverse each sentence separately. I have been able to reverse the entire string, which wasn't an issue. Then I changed my program so I am reading to the period and reversing the first sentence. However, I can't get it to read the next sentence. I believe I need a second loop but this is where I struggle. There are several questions/answers on this site that address this assignment, but none that have really taken the approach I have so they aren't relevant. At least, not from what I can tell. This is what I have:
for (String word : wordArray) {
if (word.endsWith(".") {
Stack.push(word.substring(0, word.length()-1));
break;
}
else {
Stack.push(word);
}
}
So my sentences are: "Cats are cool. Dogs are cool. So are turtles." My program will print:
"cool are Cats"
I know I need to append a period and I can figure that out later. I'm just struggling with how to create a second loop to continue reading the rest of the string.
What I need is: "cool are Cats. cool are Dogs. turtles are So."
You were thinking in the right direction: you do need one more loop to empty out the stack when the end of a sentence has been encountered, and you need some mean of storing the data (it could be an ArrayList, or a StringBuilder).
I would use a StringBuilder to store reversed sentences.
The logic of generating a reversed sentence by retrieving the elements from the stack can be extracted into a separate method. In a nutshell, it's while-loop that runs until the stack is not empty. To join the string back into a sentence, I would use a StringJoiner which facilitates combining the strings using a specified delimiter (feel free to reimplement this logic as you see fit, the point of this answer is to explain the algorithm and provide a source of inspiration rather than be a ready to go copy-past solution, for instance, you can use two StringJoiners instead of the combination StringJoiner + StringBuilder, I've only shown one possibility).
That's how it might be implemented:
public static String reverseSentences(String[] wordArray) {
Stack<String> stack = new Stack<>();
StringBuilder reversedSentences = new StringBuilder();
for (String word : wordArray) {
if (word.endsWith(".")) {
stack.push(word.substring(0, word.length() - 1));
reversedSentences
.append(createSentence(stack)) // appending the reversed sentence
.append(". "); // adding a period and a white space at the end of the sentence
} else {
stack.push(word);
}
}
return reversedSentences.toString();
}
public static String createSentence(Stack<String> stack) {
StringJoiner sentence = new StringJoiner(" "); // white space would be used a delimiter between the words
while (!stack.isEmpty()) {
sentence.add(stack.pop());
}
return sentence.toString();
}
main()
public static void main(String[] args) {
System.out.println(reverseSentences("Cats are cool. Dogs are cool. So are turtles.".split(" ")));
}
Output:
cool are Cats. cool are Dogs. turtles are So.
Before your loop, you need to create your stack like
Stack<String> wordStack = new Stack<String>();
You would do your current push operations on wordStack, and then you would pop in your second loop as you would expect.
You got very close.

Display elements of a String which are not found on the other

We were told to do a program on stings and I wasn't able to attend class because I was sick. I am asking for your help on this task that was given to us.
Create a java program that will ask the user to input two Strings. Compare the two strings and display the letters that are found on the first string but are not found on the second string.
Here is what I have at the moment https://pastebin.com/7a4dHecR
I really have no Idea what to do so any help would be appreciated!
https://pastebin.com/7a4dHecR
import java.util.*;
public class filename{
public static void main(String[] args){
Scanner sc =new Scanner(System.in);
System.out.print("Input first string: ");
String one=sc.next();
System.out.println();
System.out.print("Input second string: ");
String two=sc.next();
}
}
There are many ways to do this. I'm going to give you some parts you can put together. They are not the shortest or simplest way to solve this particular problem, but they will be useful for other small programs you write.
Here are some hints:
First, figure out how to step through your code with a debugger.
Second, figure out how to find the Javadoc for Java library classes and their methods.
You need to do something for each character in a string. Use a for loop for that:
for (int i = 0; i < one.length(); i++) {
// your code here
}
You need to get a particular character of a String.
String c = one.substring(i, i+1);
Read the Javadoc for String.substring to understand what the i and i+1 parameters do.
Now you need to find a way to check whether a String contains another String. Look at the Javadoc for the String class.
Then you can put all this together.
You could try the following:
String diff: StringUtils.difference(one, two);
System.out.println(diff);

How to loop a String ArrayList in java and how to split the elements in it

I have to write a program which prints the String which are inputed from a user and every letter like the first is replaced with "#":
mum -> #u#
dad -> #a#
Swiss -> #wi## //also if it is UpperCase
Albert -> Albert //no letter is like the first
The user can input how many strings he wants. I thought to split the strings with the Split method but it doesn't work with the ArrayList.
import java.util.*;
public class CensuraLaPrima {
public static void main(String[] args) {
Scanner s= new Scanner (System.in);
String tdc;
ArrayList <String> Parolecens= new ArrayList <String>();
while (s.hasNextLine()) {
tdc=s.nextLine();
Parolecens.add(tdc);
}
System.out.println(Parolecens);
}
}
If you want to read in single words you can use Scanner.next() instead. It basically gives you every word, so every string without space and without newline. Also works if you put in two words at the same time.
I guess you want to do something like this. Feel free to use and change to your needs.
import java.util.*;
public class CensuraLaPrima {
public static void main(String[] args) {
Scanner s= new Scanner (System.in);
String tdc;
while (s.hasNext()) {
tdc=s.next();
char c = tdc.charAt(0);
System.out.print(tdc.replaceAll(Character.toLowerCase(c) +"|"+ Character.toUpperCase(c), "#"));
}
}
}
Edit:
Basically it boils down to this. If you want to read single words with the scanner use .next() instead of .nextLine() it does consider every word seperated by space and newline, even if you put in an entire Line at once.
Tasks calling for replacing characters in a string are often solved with the help of regular expressions in Java. In addition to using regex explicitly through the Pattern class, Java provides a convenience API for using regex capabilities directly on the String class through replaceAll method.
One approach to replacing all occurrences of a specific character with # in a case-insensitive manner is using replaceAll with a regex (?i)x, where x is the initial character of the string s that you are processing:
String result = s.replaceAll("(?i)"+s.charAt(0), "#");
You need to ensure that the string is non-empty before calling s.charAt(0).
Demo.
Assuming that you've successfully created the ArrayList, I'd prefer using the Iterator interface to access each elements in the ArrayList. Then you can use any String variable and assign it the values in ArrayList . Thereafter you can use the split() in the String variable you just created. Something like this:
//after your while loop
Iterator<String> it = Parolecens.iterator();
String myVariable = "";
String mySplitString[];
while(it.hasNext()) {
myVariable = it.next();
mySplitString = myVariable.split(//delimiter of your choice);
//rest of the code
}
I hope this helps :)
Suggestions are always appreciated.

Can someone explain the Recursion in this Code

I've done HTML but that is nothing like learning java now in my AP class. So I'm pretty much brand new to coding. Today we learned about recursion and I'm pretty sure I understood it when it comes to using it like in this video.
https://www.youtube.com/watch?v=fpuWkZs51aM
But we then had to use it in a different way. We needed to make a program called WordPlay that accept any words, one at a time, until the word "STOP" is input. When stop was put in it prints them back out in reverse order. Here's the code.
import java.util.Scanner;
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Enter list of words, one per line");
System.out.println("Final word should be STOP");
wordList();
}
public static void wordList()
{
Scanner keyboard = new Scanner(System.in);
String word = keyboard.next();
if (word.equalsIgnoreCase("STOP"))
System.out.println();
else
wordList();
System.out.println(word);
}
}
So the part that I don't understand is that this works fine but when I look at the ending of wordList() it seems to me that it would just keep repeating the last word that was input. I don't get what I'm missing. Can someone explain the logic here?
The recursion does output the word that was input, however each call to wordList gets a new local variable named word (each word value is on "the stack"). If you mark it final, nothing will complain - because the word isn't modified after initialization. Also, you should probably extract the Scanner (each invocation creates a new local one of those too).
public static void wordList()
{
Scanner keyboard = new Scanner(System.in);
final String word = keyboard.next(); // <-- this is the current word.
if (word.equalsIgnoreCase("STOP"))
System.out.println();
else
wordList(); // <-- it's not STOP, recurse... which
// will get a new local word (and print it).
System.out.println(word); // <-- however, this is still current word.
}
The function will execute from top to bottom as usual, but if it enters the else block it will jump back up to the beginning like shown below. It will 'loop' exactly like this until word equals "STOP", then it'll enter the if block, print out a new line (System.out.println()) then SKIP the else block, print out word then exit the function. Brackets in the if-else statement will make this easier to see.
public static void wordList()
{
|->Scanner keyboard = new Scanner(System.in);
|
| String word = keyboard.next();
| if (word.equalsIgnoreCase("STOP")) {
| System.out.println();
| }
| else {
|---wordList();
}
System.out.println(word);
}
Its basically a recursion function or method which calls itself again and again until if condition inside it is false.
So here first new word entered by user is stored in variable called word, then if condition will check if value stored in word is Stop, if its not then again wordlist method is called and all above process is repeated again.
So each time new values entered is stored in word variable.
Thats all!!
public static int wordList()
{
Scanner keyboard = new Scanner(System.in);
String word = keyboard.next();
if (word.equalsIgnoreCase("STOP"))
{
System.out.println();
return 0;
}
System.out.println(word);
return wordList();
}
Try this
This will be the sequence of operations
1) call wordlist()
2) Get a word, say WORD1 and store in local variable word.
3) before calling wordlist recursively, WORD1 goes into stack. Stack is something like a box where you can fill say biscuits one over an other, and you can take out the biscuit that you placed last. Now the stack has WORD1
4) get another word, say WORD2 and store in local variable word. This is a new function call, even if it is recursive. So a new local variable word is allocated memory.
5) before calling wordlist recursively, WORD2 goes into stack. So now WORD2 will be the top one and WORD1 will be below in the stack.
5) get another work, now it is STOP.
6) STOP is printed
7) function returns
8) now the flow returns to previous call. Now WORD2 is popped out of stack as the local variable holding WORD2 belongs to this instance of the recursive call.
8) print WORD2 and return to previous call. Now WORD1 is popped out of the stack as the local variable holding WORD1 belongs to this instance of the recursive call
9) WORD1 printed.
Just to tell you an analogy, let us assume you have a similar task. You have to get a set of books from a friend standing besides you. You have to give him back the books in the reverse order as you got it from him as soon as he gives you a book named stop.
1) You get the book from him
2) before getting the next book, you keep it on a table, since you cannot hold this and get more books from your friend
3) yet get the next book from him
4) before getting the next book, you keep it over the first book
5) you continue doing this until you get a book named stop
6) now you start returning the books, first you will return the book named stop and as you continue, since the books are stacked, you will be returning the book in reverse order.
Hope this clarifies.
It would just repeat that last word entered if the line System.out.println(word) was before the if statement.
To understand recursion, you need the notion of the "stack". Each call to wordList() occurs in a separate level in the stack. There is a different word variable in each of these stack levels.
Since the ``System.out.println(word)` line happen after the recursive call, each of these are executed when un-piling the stack (i.e. after the previous level returns). That's why words appear in reverse order. Image: if you pile boxes one atop the other, when you un-pile them, the last box is the first to go out (hence the acronym LIFO=Last In First Out).
Another important concept for recursion is to have a way of stopping it (i.e. prevent infinite recursion). In this program, it is done when the user enters "STOP".
I like to think of these problems as a 'call stack'. Each time you 'call' the method recursively you add another 'stack'. Every recursive method needs a stopping case. In your problem the first occurrence of the word 'STOP' (how convenient) acts as your stopping case.
For example if someone enters:
"Fox"
"Bear"
"Deer"
"STOP"
As soon as the word "STOP" appears, it will be printed. Now we pick up where we left off in your 'call stack' which is the ending of
wordList()
Now the only step left is
System.out.println(word)
The word 'Deer' will be printed and now our list being printed is:
"STOP"
"Deer"
And so forth until we reach the last word.

Converting a string to an array of strings (without .split)

I'm trying to write a method that will take a sentence (a String) and convert it into an array of words (Strings) (and it will return this array). I'm looking for a manual way to do this, without .split or tokenize.
So far, all I have in terms of code is the name of my method
public String[] tokenize();
After that, I'm at a loss of where to start. Any help is appreciated, thanks.
EDIT: The string is not of fixed length, the input sentence can be anything.
You probably would want to use java.util.Scanner and construct the scanner with the string
Scanner sc = new Scanner(string);
sc.useDelimiter(\p{Space});
while(sc.hasNext)
{
string[i] = sc.next();
}
or something like that
Or, use a for loop, check each character, and chop off a substring.

Categories