How can you properly make a Stack with Integers on BlueJ? - java

I've been using BlueJ for a while now and recently, we've started making and working on Stacks and Arrays in my class. This is basically what I have to do currently:
Create the class "StackTest", which contains a Stack called "zahlen" with values of the type "Integer". Add the numbers 5, 10, 50 and 30 to the Stack respectively. Finally, run the Stack and it should show all values that are bigger than 10 in the console.
They also gave us certain keywords that have to be used at least once in the class: Keywords
import java.util.Stack;
public class StackTest
{
public StackTest(){
Stack zahlen = new Stack();
zahlen.push(5);
zahlen.push(10);
zahlen.push(50);
zahlen.push(30);
while (!zahlen.isEmpty()){
if(zahlen.top()>10){
}
zahlen.pop();
}
}
}
My problem is that first of all, I don't know what exactly the Integer in parenthesis is or what it can be used for (talking about (Integer) ) and I also don't know how you can check if the top number ( zahlen.top() ) can be used in the if command.

I think it would be genuinely worth your while to read up on the Stack class in the official Java documentation:
https://docs.oracle.com/javase/8/docs/api/java/util/Stack.html
It can be a bit dense, but it contains a lot of useful information. This will give you the info you need regardless of using BlueJ, Eclipse, or any other IDE. :-)

A stack follows LIFO rule (Last-In-First-Out). Think of a stack like a stack of dirty plates that you want to clean, to clean a plate you would take a plate on top of the stack rather than reach for the bottom or the middle. In your case rather than a stack of dirty plates, it's a stack of Integers.
Once you've created your stack collection, you push() elements into the stack in your code example it would look something like this:
|30|
|50|
|10|
|5 |
¯¯
Note that you don't have access to any of elements aside from the top of stack (30 in this case). To gain access to elements below you have to pop() the stack which will remove it from the collection.
For example:
int value = zahlen.pop();
will cause value to be equal to 30 and your new stack collection will look like this:
| |
|50|
|10|
|5 |
¯¯
You can now use value to check whether or not it's greater than 10 then use
System.out.println() to print out the value to the console, simply loop this till your stack is empty. If you wish to look at the value on top of the stack without popping it off you can use peek() method.

Related

Practicing Java, need help finding the output

I am looking to find the output of the following code.
Suppose that myStack is a linked implementation of a stack of Integers.
What would the output be for this code?
myStack.push(new Integer(1));
myStack.push(new Integer(2));
System.out.println(myStack.pop());
System.out.println(myStack.pop());
System.out.println(myStack.pop());
If this is the only code, then I believe it should throw a run time exception because you try to pop an element out of a stack when the stack size is zero.
So your output would be something like:
2
1
Error!!!!
Though that third line really depends on how your pop() method handles a stack with zero size.

Is my analysis of space complexity correct?

This is problem 9.5 from Cracking the Coding Interview 5th edition
The Problem: Write a method to compute all permutations of a string
Here is my solution, coded in Java(test it, it works :) )
public static void generatePerm(String s) {
Queue<Character> poss = new LinkedList<Character>();
int len = s.length();
for(int count=0;count<len;count++)
poss.add(s.charAt(count));
generateRecurse(poss, len, "");
}
private static void generateRecurse(Queue<Character> possibles, int n, String word) {
if(n==0)
System.out.println(word);
else {
for(int count=0;count<n;count++) {
char first = possibles.remove();
generateRecurse(possibles, n-1, word+first);
possibles.add(first);
}
}
}
I agreed with the author that my solution runs in O(n!) time complexity because to solve this problem, you have to consider factorials, like for a word like "top", there are three possibilities for the first letter, 2 for the second and so on....
However she didn't make any mention of space complexity. I know that interviewers love to ask you the time and space complexity of your solution. What would the space complexity of this solution be? My initial guess was O(n2) because there are n recursive calls at each level n. So you would add n + n - 1 + n - 2 + n - 3.....+ 1 to get n(n+1)⁄2 which is in O(n2). I reasoned that there are n recursive calls, because you have to backtrack n times at each level and that space complexity is the number of recursive calls your algorithm makes. For example, when considering all the permutations of "TOP", at level, 3 recursive calls, gR([O,P],2,"T"), gR([P,T],2,"O"), gR([T,O],2,"P") are made. Is my analysis of space complexity correct?
I think you got the right answer but for the wrong reason. The number of recursive calls doesn't have anything to do with it. When you make a recursive call, it will add a certain amount of space to the stack; but when that call exits, the stack space is released. So suppose you have something like this:
void method(int n) {
if (n == 1) {
for (int i = 0; i < 10000; i++) {
method(0);
}
}
}
method(1);
Although method calls itself 10000 times, there will still be no more than 2 invocations of method on the stack at any one time. So the space complexity would be O(1) [constant].
The reason your algorithm has space complexity O(n2) is because of the word string. When n gets down to 0, there will be len stack entries being taken up by invocations of generateRecurse. There will be len stack entries at most, so the space usage of the stack will only be O(n); but each of those stack entries has its own word, which will all exist on the heap at the same time; and the lengths of those word parameters are 1, 2, ..., len, which of course do add up to (len * (len+1)) / 2, which means the space usage will be O(n2).
MORE ABOUT STACK FRAMES: It appears that an explanation of the basics of stack frames would be helpful...
A "stack frame" is just an area of memory that's part of the "stack". Typically, the stack is a predefined area of memory; the location and size of stack frames, however, are not predefined. When a program is first executed, there won't be anything on the stack (actually, there will probably be some initial data there, but let's say there's nothing, just to keep things simple). So the stack area of memory looks like this:
bottom of stack top of stack
------------------------------------------------------------------
| nothing |
------------------------------------------------------------------
^
+--- stack pointer
(This assumes that the stack grows upward, from lower to higher addresses. Many machines have stacks that grow downward. To simplify, I'll keep assuming that this is a machine whose stack grows upward.)
When a method (function, procedure, subroutine, etc.) is called, a certain area of the stack is allocated. The area is enough to hold the method's local variables (or references to them), parameters (or references to them), some data so that the program will know where to go back when you return, and possibly other information--the other information is highly dependent on the machine, the programming language, and the compiler. In Java, the first method will be main
bottom of stack top of stack
------------------------------------------------------------------
| main's frame | nothing |
------------------------------------------------------------------
^
+--- stack pointer
Note that the stack pointer has moved up. Now main calls method1. Since method1 will return to main, the local variables and parameters of main have to be preserved for when main gets to resume executing. A new frame, of some size, is allocated on the stack:
bottom of stack top of stack
------------------------------------------------------------------
| main's frame | method1's frame | nothing |
------------------------------------------------------------------
^
+--- stack pointer
and then method1 calls method2:
bottom of stack top of stack
------------------------------------------------------------------
| main's frame | method1's frame | method2's frame | nothing |
------------------------------------------------------------------
^
+--- stack pointer
Now method2 returns. After method2 returns, its parameters and local variables will no longer be accessible. Therefore, the entire frame can be thrown out. This is done by moving the stack pointer back to where it was before. (The "previous stack pointer" is one of the things saved in some frame.) The stack goes back to looking like this:
bottom of stack top of stack
------------------------------------------------------------------
| main's frame | method1's frame | nothing |
------------------------------------------------------------------
^
+--- stack pointer
This means that, at this point, the machine will see the portion of the stack starting with the stack pointer as "unused". It's not really correct to speak of method2's frame being reused. You can't really use something that has ceased to exist, and method2's frame no longer exists. Conceptually, all there is is a big empty area of the stack. If method1 calls another method, whether it's method2, method1 recursively, System.out.println, or something else, a new frame will be created at the place where the stack pointer is now pointing. This frame could be smaller, equal, or larger in size than the method2 frame used to be. It will take up part or all of the memory where the method2 frame was. If it's another call to method2, it doesn't matter whether it's called with the same or different parameters. It can't matter, because the program doesn't remember what parameters were used last time. All it knows is that the area of memory starting with the stack pointer is empty and available for use. The program has no idea what frame most recently lived there. That frame is gone, gone, gone.
If you can follow this, you can see that when computing the space complexity and when looking just at the amount of space used by the stack, the only thing that matters is, how many frames can exist on the stack at any one point in time? Frames that may have existed in the past but no longer do are not relevant to the computation, no matter what parameters the methods were called with.
(P.S. In case anyone was planning to point out how I'm technically wrong about this or that detail--I already know that this is a gross oversimplification.)

The Swedish Chef Translator

So the context is, I have a CS project where input is taken in either word or sentence form, and then it is translated to what The Swedish Chef from The Muppets would say. I decided to take the input as one line of string, and send that line into a parser, which in turn would build an array out of translations of the input's letters. The conditions for what gets changed are defined within. the current error I am getting: (while using "INPUT" as input)
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 1
at java.util.ArrayList.rangeCheckForAdd(Unknown Source)
at java.util.ArrayList.add(Unknown Source)
at SwedishTranslator.parseString(SwedishTranslator.java:62)
at SwedishTranslator.main(SwedishTranslator.java:12)
Currently it is supposed to just print the array, I wanted to worry about formatting after the fact.
The code:
Sorry for the walls of text but I can't find where the issue is exactly and I figured I would give it a shot here. Thanks in advance.
ind<=in.length() goes one step too far.
Use ind < in.length() or ind <= in.length() - 1
The error arrises on line 62 which I assume is in your big if else section.
Within there you have several ind++ calls. This increments the pointer you use in the loop. So if your code must go through several of these statements it will go beyond the array index.
Additionally you have an issue in the for loop as joval mentioned
Edit
The ++ unary operator increments the variable (-- decrements). Placing the ++ after the variable name (x++) will increment before evaluation, where ++x will increment after evaluation.
This is a common test question for CS students so I suggest you do some more research and practice regarding the operator.
You're making a couple of really understandable beginner mistakes here. Instead of explicitly fixing your code, I'll tell you about a couple of things that, if considered while reviewing and editing your code, will also fix your problem.
The documentation for String.charAt http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#charAt(int) throws an error when you attempt to access out-of-bounds items in the String. Make sure that you check that you're not attempting to look beyond the length of the String before you go calling charAt all willy-nilly! If you're currently "considering" the 'T' in "INPUT" and you go trying to look at the next two characters, Java will complain.
Second, and this is more of a general thing (though it does need to be fixed in your code above); the '++' operator doesn't do what you appear to think it actually does. When you do this: in.charAt(ind++)=='H', you may think you're just checking on the value at the next index, but you're actually advancing the index at the same time! The '++' operator is very handy, but it has a side affect that trips up a lot of beginners: it assigns itself + 1 to itself! That means that if you're on the 'I' in "INPUT" and somewhere within your loop you call ind++ once, you'll be on 'P' at the next iteration of your loop! When you see '++' remember that you're changing the value of the variable.
Good luck!

Manual String Find and Replace [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Given a string I #eat# #hamburgers# and a StringBuilder eat: [eat, consume, like] hamburgers: [hamburgers, spinach, bananas], I want to randomly replace the words within hashmarks with randomly chosen ones from their wordbanks, so that phrases such as I like bananas and I consume spinach will be generated. Code to randomly select another word, given a token (i.e. eat, hamburgers) has been written.
I need to use this regex #[^#]+# to find words within the initial string contained by hashmarks, pass them to the replace method, and then put their random correlates back inside the initial string. I tried using StringTokenizer, but realized it's not the tool for the job.
I need to somehow extract the first word within hashmarks and pass it to the method calling for its replacement before calling the method archetypeString(#[^#]+#, replacement) in such a way so that when the loop runs again, both the word grabber&passer-to method and the replacement method are then working with the second hashed word.
tokenizer dead-end:
StringTokenizer stt = new StringTokenizer(archetype);
while(stt.hasMoreTokens()){
String temp = stt.nextToken();
if(temp.charAt(0)=='#');
}
and the getPhrase method:
public List<String> getPhrases(StringBuilder fileContent, String token) {
StreamTokenizer tokenizer = new StreamTokenizer(new StringReader(fileContent.toString()));
List<String> list = new ArrayList<String>();
try {
while (tokenizer.nextToken() != StreamTokenizer.TT_EOF) {
if (tokenizer.sval.equals(token)) {
tokenizer.nextToken(); // '['
do {
tokenizer.nextToken(); // go to the number
list.add(String.valueOf(tokenizer.sval));
} while (tokenizer.nextToken() == ',');
break;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
I need to use this regex #[^#]+# to find words within the initial string contained by hashmarks, pass them to the replace method, and then put their random correlates back inside the initial string. I tried using StringTokenizer, but realized it's not the tool for the job.
It is not clear from your question whether this is part of some sadistic homework assignment or just the first way you thought of to solve whatever problem you're trying to solve. This is not a regular expression problem any more than it's a StringTokenizer problem.
Look at String.format(), and the formatting capabilities of Formatter. I do not understand why you would ever need to know what the last string you generated was if your object is to generate the next one at random. Just pick a new random value and format it with String.format().
--
After reading your comment to this answer and looking at the question you referred to, I'm going to make a couple of recommendations.
(1) start with a simpler coding assignment or two, something without regular expressions. Make sure you absolutely understand the following concepts: instance variables. variable scope. public methods versus private methods. passing parameters to methods, and returning values from methods. You can do quite a bit with just that much. You don't need to study inheritance until you have all of those down cold, and I recommend that you do not try.
(2) for each coding assignment for at least your first 5, make sure you have written out what your program is to be provided as data and what output it is supposed to produce. List any constraints someone has given you separately (must use class X, must display error message, whatever).
(3) Put opening braces and closing braces on lines by themselves; match each opening brace with a closing brace indented the same amount. Indent code within each pair of braces another 2 or 3 spaces further to the right. This means that brace pairs inside other brace pairs will be indented further. I know this is not the way you see most code, and plenty of people will tell you that it is "wrong". But until you get comfortable with scope and whether a given place in your code is inside or outside a method or a loop, I think it best that you give yourself these extra visual cues. For someone not familiar with other ways of doing things, this is easiest.
(4) be careful of your terms when posting here. In the other question you refer to, you say it is about inheritance, but it uses "implements", indicating that it is implementing an interface, not inheriting from a class. It is confusing to those of us trying to help you if you get the terminology wrong.
(5) when you post here: post the entire program (these early assignments should all be under 100 lines total, no reason not to post all of it). Make sure it is properly indented; use spaces instead of tabs. In text, and maybe also in comments, point out the place in the code where you seem to have the problem (if you know). If there is an error message, post the entire error message (don't tell us what it is, and don't try to interpret it for us). Work on your code until you have a specific question: why do I get a compile error here? Why do I get (or fail to get) this output? The program outputs X but I expected Y, why is that? etc.
We're not a tutorial shop; most of us need instruction to learn to program, and you need to get most of that somewhere besides here. We are willing to help with your questions, given that your questions are specific and reasonable and you aren't expecting us to provide the instruction. By itself, "I'm lost and need help" is a bit beyond StackOverflow's normal way of operating.

Format java string to look a specific way

I am new to Java and I have 4 int stacks that I need to print out in a specific way. The IDE I am using is BlueJ.
I want to print the arrays to look like the following
|110| |231| |333| |444|
|111| |232| |334| |447|
|112| |233| |335| |448|
|113| |234| |336| |449|
|114| |235| |337| |450|
|115| |236| |338| |451|
I am trying to this with System.out.println("|"+stack1.pop()+"|") but it creates a problem because I am not sure how to go back from the bottom, back to the top. Ex. 115 --> back up to 231. Each column represents a stack.
Thank you!
Use String.format() better than concatenating a bunch of strings
System.out.println(String.format("|%s|\t|%s|\t|%s|\t|%s|",
stack1.pop(),stack2.pop(),stack3.pop(),stack4.pop()));
If you want to print the Stack elements in the opposite order, just reverse the stack first
You wont be able to do that in console:
as an alternative you can print values from each stack and then moving down like:
System.out.println("|"+stack1.pop()+"|\t|"+stack2.pop()+"|\t|"+stack3.pop()+"|\t|"+stack4.pop()+"|" );
Edit
as commented - you can use String.format(...) , check here for formatting options available
How about this :
ArrayList<Stack<Integer>> arrays=new ArrayList<Stack<Integer>>();
arrays.add(stack1);
arrays.add(stack2);
arrays.add(stack3);
arrays.add(stack4);
//Put some code here to Determine the stack size, if all are unequal in size
int size=stack1.size();
for(int i=0;i<size;i++){
String value="";
String temp="";
//4 = if you know the number of stacks is going to be 4 only
for(int j=0;j<4;j++){
//Handle here Empty Stack Exception and print blank
value="|"+(String)(arrays.get(j)).pop().toString()+"|"+" ";
temp=temp+value;
}
System.out.println(temp);
}

Categories

Resources