Doing this for my project, using jFrame.
My problem is, when I input first:1 , Second: 2 , third: 3
and I clicked view stack, and the problem shows [ 1 , 2 , 3 , 0 , 0 , 0 . . . ]
I think the view should be [ 3 , 2 , 1 , 0 , 0 . . . .]
what what I understood about push.
code used :
// Global Variable
int[] myStack = new int [10];
int top = -1;
// Push Button
if ( top == 9){
JOptionPane.showMessageDialog(null, "Stack Full!");
}else{
int val = Integer.parseInt(pushtxt.getText());
top++;
myStack[top] = val;
pushtxt.setText("");
}
}
// View Stack Button
if (top == -1){
JOptionPane.showMessageDialog(null, "Stack Empty!");
}else{
viewtxt.setText("");
for (int x=0; x<=9; x++){
viewtxt.setText(viewtxt.getText()+" "+ myStack[x]);
}
}
I think you're misunderstanding the way a stack works. More specifically, the algorithm you use to display the stack is incorrect. In your case, you start at the bottom of the stack (where x=0) and work your way towards the top (actually, beyond the top, where x=9). This is why your output seems reversed to you (it's also full of zeros that you shouldn't be printing).
When displaying the stack, you should start at the top (x=2) and work your way towards the bottom (x=0). If you do things this way, then the output will be correct.
Stacks are FiLo, First in, last out. Generally stacks are used in a manner where you push items (the first being the bottom of the stack) and they keep on stacking. When you need to get values off of the stack you pop, going back in reverse order.
So the order you entered for data would store as:
1,2,3
bottom -> top
Your data is correct, it is as it should be.
So next you'll want to write a pop function, where you grab the value at the top of the stack and then decrement the top variable.
Popping your stack one at a time would return in the following order:
3
2
1
From what you were describing, I think perhaps you were going to pop from the front of the stack? If that is what you want to do, you would have to shift all of your values every-time you pushed a new value. What you currently have now is better code than shifting all your values on every push =]
You are on the right track.
EDIT I have not used swing in a while, but hopefully this will lead you in the right direction (I looked at some old code to make sure my syntax was correct, have not tested though). To answer the question you asked in my comment, your code would look something similar to the following for the pop function and setting the text for the popTextField
your pop function should look something like the following:
/**
* The code for the button press could be as simple as follows
*/
popBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0){
try{
popTextField.setText(popStack);
}catch(IndexOutOfBoundsException e){
popTextField.setText("The stack is empty");
}
}
});
the pop function can be really simple. You do not need to use exceptions - but it is good practice.
/**
* Simple Pop function
*/
private int popStack(){
if(top >= 0){
return myStack[top--];
}else{
throw new IndexOutOfBoundsException("The stack is empty");
}
}
Related
my Main contains a conveyor, which transports a carton (my agent) from A to B. I added a radio button with which the user can choose the size of the box ("small", "medium", "big" & "very big"). I now want every carton to save the value of the radio button. I tried a lot of different stuff like linking it to a parameter, but I didn't manage to figure it out.
Picture of my model:
the code I used for the radio button is:
if( value == 0 )
radioValue = 1;
else if( value == 1 )
radioValue = 2;
else if( value == 2 )
radioValue = 3;
else if( value == 3 )
radioValue = 4;
radioValue being the parameter in the Main i linked my radio-button to.
How do I give this parameter to the agent and how do I read it out later?
Thanks in advance for helping!
in your Kist agent create a variable called size of type int.
in the source block, in the properties, on the "on at exit" action, under the action section of the properties write the following code:
agent.size=radioValue;
This is one of the most basic things to do in AnyLogic... so I suggest for you to go through a training before even starting to work on any model. This can be done by going through the tutorials, the anylogic in 3 days book or my course here: noorjax.teachable.com/p/anylogic
later you can use agent.size to access the size of your agent, in any of the blocks.
Without seeing more of the code, my general suggestion would be to consider looping through the agents (e.g., with a for loop) and having them all set a local variable cartSize equal to radioValue (I wouldn't use "size" because its also used for agentsets I believe). Just spitballing here, but something like this?
for (int x = 0; x < carton.size(); x++) {
carton.get(x).cartSize = radioValue;
}
Hi I am making an android App, I want to add some values to a database and I want to do N times so I used a for loop as seen below:
private void addCodeToDataBase() {
for (int i = 1; i <= 100; i++) {
//indexnumber is a TextView
indexNumber.setText("Please enter the TAN code for Index number " + i);
//tanCode is an EditText
if (tanCode.getText().toString() != null) {
//index here is just an int so i can use the i inside the onClick
index = i;
//add is a button
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String codeText = tanCode.getText().toString();
dbHandler.addcode(index, codeText);
}
});
} else {
Toast.makeText(addcode.this, "Please enter your code !!!", Toast.LENGTH_LONG).show();
}
}
}
but what I am facing here is the for loop jumps to 100 at the first run, What I mean is the text will show :
Please enter the TAN code for Index number 100
it skips 99 numbers!! how would I fix it ?
It's Because your for loop executes so fast that you can't notice that the change of the text.First i is 0,and then it becomes 1,then the text will be "Please enter the TAN code for Index number 1" ......
your loop is working correctly but it is replacing text on each iteration that's why you think that it is jumping on last value please use break point and debug you will see each value on each iteration or use log in which you will see each value
It's not easy to imagine what your code does without seeing your declarations of indexNumber, tanCode, index, and, in particular, add. So, e.g., we don't know how often your if condition yields true.
However, most probably, the problem is that your assignment add.setOnClickListener(...) is just iterated with no user interaction in between. Now if you repeatedly assign something to your add (whatever that is), the last assignment will win.
If you want 100 buttons, you'll need to have an array or List of buttons to press, where each has a different tan code. If you want one button that repeatedly asks for the different tans, then you have to assign the data for click i + 1 only after click i has been handled, i.e. in the on click listener.
To give more specific help, we would need to know how your user interface should look (how many widgets of what kind) and how each widget should behave.
I'm creating an A* search at the moment ( wiki page with pseudocode ) and I've been spending the last hour or so coming up with heuristic equations. When I think I finally found a good one, I removed the print statement that was allowing me to see what states were being visited. For some reason, that made my search go much much slower. If I add the print back in, it becomes fast again. What could possibly be going on?
I even tried changing what it prints. No matter what I am printing (as long as it is 2 characters or more), the result is the same.
Some of the code:
I apologize beforehand for messy code, this is my first time working with something like this:
while(!toVisit.isEmpty()){//toVisit is a set of states that need to be visited
int f = Integer.MAX_VALUE;
State temp;
State visiting = new State();
Iterator<State> it = toVisit.iterator();
while(it.hasNext()){//find state with smallest f value
temp = it.next();
if(temp.getF() < f){
f = temp.getF();
visiting = temp;//should be state with smallest f by end of loop
}
}
System.out.println("Visiting: ");//THIS LINE HERE
//LINE THAT MAGICALY MAKES IT FAST ^^^^
if(numConflicts(visiting.getList()) == 0){//checking if visiting state is the solution
best = visiting.getList();//sets best answer
return visiting;//ends algorithm
}
........
info on toVisit and visiting.getList():
HashSet<State> toVisit = new HashSet<State>();//from Java.util
public ArrayList<Node> State.getList(){return list;}
Node is my own class. It only contains some coordinates
This consistently solves the problem in about 6 seconds. If I change that line to print nothing or something shorter than about 2 characters, it takes anywhere from 20 to 70 seconds
I am making a basic color guessing game (my firstone) where you get a hex code and you'll get some color alternatives to chose from. However, I've run into some problems. The way I have it set up is that I create some ovals to which I assign random colors (one with the correct one) and that is working all fine.
The problem is that in order for the answer not to be put at the same spot every time I'm trying to randomly generate positions for these ovals, but my code doesn't work. The code (which I thought would reserve spots and assign spots) doesn't reserve spots correctly. I thought it would only go into the else statement if the positions wasn't taken (takenPos[tempRandomNum] == false) but it seems that it always goes into the else statement, even if my print confirms that it generated the same spot multiple times.
Another problem is that if it enters the If statement (which it doesn't right now), generates a new value, and that value is taken it uses the value anyway.
Print:
ELSE false 0
ELSE false 540
ELSE false 0
ELSE false 360
ELSE false 360
ELSE false 450
ELSE false 180
ELSE false 360
ELSE false 540
Code:
public int randomOvalPos() {
//An array of booleans to keep track of if the position is taken.
boolean[] takenPos = new boolean[difficulty];
//Temporary variable to return if it gets through the if statement.
int tempRandomNum = randomNum(0 , difficulty - 1);
//Check if the position is taken (set before return).
if(takenPos[tempRandomNum]){
//If the position is taken I want it to get a new random position.
//The problem is that if this spot is taken as
//well I can't just keep redoing it.
tempRandomNum = randomNum(0, difficulty - 1);
takenPos[tempRandomNum] = true;
return tempRandomNum * 90;
}else{
//If it isn't taken set the boolean to true and return the value.
takenPos[tempRandomNum] = true;
return tempRandomNum * 90;
}
}
What I would do (before displaying the ovals to the user) is use the code that currently works and places the answer in the same spot every time, and then shuffle the array using a Fischer-Yates shuffle
Read this question for an implementation on how to do that: Random shuffling of an array
Ok, so I have a 3 x 3 jig saw puzzle game that I am writing and I am stuck on the solution method.
public Piece[][] solve(int r, int c) {
if (isSolved())
return board;
board[r][c] = null;
for (Piece p : pieces) {
if (tryInsert(p, r, c)) {
pieces.remove(p);
break;
}
}
if (getPieceAt(r, c) != null)
return solve(nextLoc(r, c).x, nextLoc(r, c).y);
else {
pieces.add(getPieceAt(prevLoc(r, c).x, prevLoc(r, c).y));
return solve(prevLoc(r, c).x, prevLoc(r, c).y);
}
}
I know I haven't provided much info on the puzzle, but my algorithm should work regardless of the specifics. I've tested all helper methods, pieces is a List of all the unused Pieces, tryInsert attempts to insert the piece in all possible orientations, and if the piece can be inserted, it will be. Unfortunately, when I test it, I get StackOverflow Error.
Your DFS-style solution algorithm never re-adds Piece objects to the pieces variable. This is not sound, and can easily lead to infinite recursion.
Suppose, for example, that you have a simple 2-piece puzzle, a 2x1 grid, where the only valid arrangement of pieces is [2, 1]. This is what your algorithm does:
1) Put piece 1 in slot 1
2) It fits! Remove this piece, pieces now = {2}. Solve on nextLoc()
3) Now try to fit piece 2 in slot 2... doesn't work
4) Solve on prevLoc()
5) Put piece 2 in slot 1
6) It fits! Remove this piece, pieces is now empty. Solve on nextLoc()
7) No pieces to try, so we fail. Solve on prevLoc()
8) No pieces to try, so we fail. Solve on prevLoc()
9) No pieces to try, so we fail. Solve on prevLoc()
Repeat ad infinitum...
As commenters have mentioned, though, this may only be part of the issue. A lot of critical code is missing from your post, and their may be errors there as well.
I think you need to structure your recursion differently. I'm also not sure adding and removing pieces from different places of the list is safe; much as I'd rather avoid allocation in the recursion it might be safest to create a list copy, or scan the board
so far for instances of the same piece to avoid re-use.
public Piece[][] solve(int r, int c, List<Piece> piecesLeft) {
// Note that this check is equivalent to
// 'have r and c gone past the last square on the board?'
// or 'are there no pieces left?'
if (isSolved())
return board;
// Try each remaining piece in this square
for (Piece p : piecesLeft) {
// in each rotation
for(int orientation = 0; orientation < 4; ++orientation) {
if (tryInsert(p, r, c, orientation)) {
// It fits: recurse to try the next square
// Create the new list of pieces left
List<Piece> piecesLeft2 = new ArrayList<Piece>(piecesLeft);
piecesLeft2.remove(p);
// (can stop here and return success if piecesLeft2 is empty)
// Find the next point
Point next = nextLoc(r, c);
// (could also stop here if this is past end of board)
// Recurse to try next square
Piece[][] solution = solve(next.x, next.y, piecesLeft2);
if (solution != null) {
// This sequence worked - success!
return solution;
}
}
}
}
// no solution with this piece
return null;
}
StackOverflowError with recursive functions means that you're either lacking a valid recursion stop condition or you're trying to solve too big problem and should try an iterated algorithm instead. Puzzle containing 9 pieces isn't too big problem so the first thing must be the case.
The condition for ending recursion is board completion. You're only trying to insert a piece in the for loop, so the problem is probably either that the tryInsert() method doesn't insert the piece or it doesn't get invoked. As you're sure that this method works fine, I'd suggest removing break; from
if (p.equals(prev[r][c]))
{
System.out.println("Hello");
break;
}
because it's the only thing that may prevent the piece from being inserted. I'm still unsure if I understand the prev role though.