Program freezing on run - java

I am trying to create a program that works as a "math help calculator" and it asks you questions. I have a button on the calculator to ask you a new question and I want to be able to ask a maximum of ten questions. So I figured why not make a for loop where the button to ask a new questions makes the increment which will then prompt the new question. PROBLEM: for some reason unless I make it i++ in the for loop it's self. My program freezes. No syntax or run time errors but the java program freezes. I guess in theory it would work but I am doing something wrong?
for(int i = 0; i < 10;){
if(e.getSource() == cmdNew){
i++;
}

Your increment is in the incorrect place.
for(int i = 0; i < 10; i++) {
if(e.getSource() == cmdNew) {
}
}

You are in an infinite loop. (e.getSource() == cmdNew) is never true so i never gets incremented and you just loop forever.

Related

While loop doesn't continue even though condition still holds true

I was tasked to create a simulation of a Bank. So far the progress I've made are generating random Client objects, making 4 objects of Teller, putting the Client objects into a circular queue and putting a Client into an empty Teller if there are any.
The problem I have now is that the while loop I made does no continue even though the set condition is still true, it can only execute 5 times. The program still runs though.
This is the code I have so far(assume all variables are declared):
public void run() {
int counter = 1;
populateTellers(windowArray);
while (counter < 10) {
newClient = generateClient();
System.out.println(newClient.toString() + " arrived at :" + counter);
System.out.println();
clientQueue.enqueue(newClient);
clientList.add(newClient);
System.out.println("The Queue now contains " + clientQueue.numberOfOccupiedCells() + " Client(s):");
for (int x = 0; x < clientList.size(); x++) {
System.out.println(clientList.get(x).toString());
}
System.out.println();
arrayIndex = getATeller(windowArray);
if (arrayIndex != -1) {
clientList.remove(0);
clientQueue.dequeue();
windowArray[arrayIndex].setClient(newClient);
windowArray[arrayIndex].setServiceTime(newClient.getDuration());
System.out.println(windowArray[arrayIndex].getName() + " now serves " + newClient.toString());
} else {
for (int x = 0; x < clientList.size(); x++) {
if (windowArrray[arrayIndex].getServiceTime() == counter) {
windowArray[arrayIndex].setClient(new Client());
System.out.println(windowArray[arrayIndex].getName() + " ends service for " + newClient.toString());
}
}
}
counter++;
}
}
The one thing that I can't get head around is that when I remove the code from aI = getATeller(wA); 'till the closing bracket of the if statement below it the program would work. I've tried putting the block into a method, changing the positions of the codes inside if(){} and else{} and changing the condition to if(aI==1), still I got no improvements. Any idea on what I'm doing wrong?
EDIT: So I've been able to narrow it down to a line of code which is windowArray[arrayIndex].setServiceTime(newClient.getDuration());, whenever I assign a value to a Teller's service time the problem would occur, I've checked my Teller class and there was no error there. Any ideas how I can solve this.
Why is it only executing 5 times? According to the code, counter is used as the used to check if it should continue looping for not. The only instance where counter is changed is at last line: counter++.
I can guess that you did a System.out.print on the counter, and it ends up to 5, and it magically stops. Most likely it's throwing an exception, which is not caught, and is lost in the void.
Edit: If this piece of code is being run on another thread, then maybe it's hanging up on some function. Do as told here
Try to find where your loop was turning to infinite loop,
Try writing printing statements, wherever necessary, just to find the flow of execution.
Then printout your variable values, too check whether they were as expected, keep on narrowing your scope as you find error occurred in certain scope, then you will find the culprit, if it is leading you to some other function, then thoroughly check that particular function.

Why does nothing happen when a "if ... <=0" criteria is met?

I have a player controlled object which is set to 100 health. With each hit from an enemy it goes down. The problem is, after it reaches 0 health, it still keeps going further into the negatives. I have a popup set
private void playerHealth(){
if (player.health <= 0)
JOptionPane.showMessageDialog(null, "you lose");
System.exit(0);
}
so that in theory, it should pop up after health is <=0. However, when I try to run it, it just opens and closes immediately. I can see the window for a split second. If I delete the
JOptionPane.showMessageDialog(null, "you lose");
System.exit(0);
and replace it with say,
player.isAlive = false;
(isAlive is set true for player, enemies and all bullets), the health will continue to decrease past the negatives.
This part might help as well: Its the code to delete the dead enemies and bullets, there is nothing similar for player, so that may be the problem.
private void removeDead(){
for (int i = 0; i <bullets.size(); i++){
if (bullets.get(i).isAlive == false )
bullets.remove(i);
}
for (int i = 0; i <mobs.size(); i++){
if (mobs.get(i).isAlive == false )
mobs.remove(i);
}
for (int i = 0; i <mobBullets.size(); i++){
if (mobBullets.get(i).isAlive == false )
mobBullets.remove(i);
}
bullets.trimToSize();
mobs.trimToSize();
mobBullets.trimToSize();
}
So any help is appreciated. Thank you. (all the code is from an online tutorial, which is why I dont know anything.)
If you want both statements to be executed, surround them in a block :
private void playerHealth() {
if (player.health <= 0) {
JOptionPane.showMessageDialog(null, "you lose");
System.exit(0);
}
}
Without the curly braces, System.exit(0); is not part of the if statement and will always be executed, which explains the it just opens and closes immediately.
I agree with the previous answer.
However, you need to know how to avoid such problems in the future. Use an IDE or other editor that will automatically indent your code for you. Here is what one did to the failing if-statement:
private void playerHealth() {
if (player.health <= 0)
JOptionPane.showMessageDialog(null, "you lose");
System.exit(0);
}
The problem becomes much more obvious.
It looks like you missed a { on your if statement, if you want to execute a block of code in an if statement you need to do
if(something){
response;
}
So it should be this:
private void playerHealth() {
if (player.health <= 0) {
JOptionPane.showMessageDialog(null, "you lose");
System.exit(0);
}
}

Method calling and display issue

I am new to java and the coding is probably sloppy so please don't be harsh! Anyways, I am making a method that will set increase in turn by 1 each time I hit the end turn button.
public int turns (int turn){
int turns = 0;
if (turn == 0){
btnYes.setEnabled(false);
btnNo.setEnabled(false);
btnRolldie.setEnabled(true);
btnPurchase.setEnabled(true);
btnMove.setEnabled(true);
turn++;
}
if (turn == 1){
btnYes.setEnabled(false);
btnNo.setEnabled(false);
btnRolldie.setEnabled(true);
btnPurchase.setEnabled(true);
btnMove.setEnabled(true);
turn++;
}
if (turn == 2){
btnYes.setEnabled(false);
btnNo.setEnabled(false);
btnRolldie.setEnabled(true);
btnPurchase.setEnabled(true);
btnMove.setEnabled(true);
turn++;
}
if (turn == 3){
btnYes.setEnabled(false);
btnNo.setEnabled(false);
btnRolldie.setEnabled(true);
btnPurchase.setEnabled(true);
btnMove.setEnabled(true);
turn = 0;
}
return(turns);
}
private void btnEndTurnActionPerformed(java.awt.event.ActionEvent evt) {
int turns = 0;
lblturn.setText("" +turns(turns));
When I run the program, the label constantly repeats 0 whenever I hit the button. I was thinking that int turns; would work, but the variable isn't initialized. I do not know if there is an error in my method, or if the initialization in the button is overriding the method.
As I said, i'm new to java so this might be the entirely wrong approach, and if it is, please give me some recommendations on how to improve this kind of structure. Thanks!
int turns = 0; on the second line is a local variable so the value get reset every time the method is called. You need to make it as a field of a class so that it can be shared between method. And also change turn++ to turns++.
You should be having turns++ not turn++

In Java, when is a "do while" loop the only option?

Is there ever a situation where you must use a do while loop? Is it an accepted practice? It seems like it is equivalent to a plain while loop except that its first iteration happens before checking the conditional, if that is even true.
int i = 3;
while ( i > 0 ) { // runs 3 times
i--;
}
vs
int j = 3;
do {
j --;
} while ( j > 0 ); // runs 3 times
The same?
EDIT: I have seen the java doc, but
the example in the java docs doesn't look like it requires that the particular routine inside of the do while loop must be run in the do while loop instead of inside of a regular while loop!
Is there ever a situation where you must use a do while loop?
No: every do-while loop can be written as a while-loop by running the body once before the loop begins. However, there are certainly cases where it makes more sense to use the do-while construct (i.e. if you always want the loop to iterate at least once), which is why it exists in the first place.
Is it an accepted practice?
If you use it appropriately, then yes absolutely.
It seems like it is equivalent to a plain while loop except that its first iteration happens before checking the conditional, if that is even true.
That's right. You can read more about do-while in its tutorial.
This example maybe help you be clearer:
int i = 3;
System.out.print("while: ");
while (--i > 0){
System.out.print("x");
}
System.out.print("\ndo-while: ");
int j = 3;
do
{
System.out.print("x");
}while (--j > 0);
This prints
while: xx
do-while: xxx
A real time example.
There is a contest with 5 level.
In each level if you score 100 you can proceed to next level.
Less code for do while, but not for while.
boolean playContest()
{//do while
int level = 1;
int score;
do
{
score = 0;
score = play();
}while(score>99 && level++<6)
if(level>4 && score>99)
isWinner = true;
else
isWinner = false;
return isWinner;
}
boolean playContest()
{//while
int level = 1;
int score;
while(level <6)
{
score = 0;
score = play();
if(score < 100)
break;
level++;
}
if(level>4 && score>99)
isWinner = true;
else
isWinner = false;
return isWinner;
}
basic difference between while and do-while is do while will be executed at least once.
when do-while is best option?
in case when you want to execute some actions till you meet condition, of course you could achieve same thing by using while but early termination of loop with break, is nasty and ugly solution
When you want to execute the statement inside do for at least once, then you can go for it.
Directly from Docs
The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once,
do {
statement(s)
} while (expression);
No, there is no time a do-while loops is the only option, it is used for convenience when you do not want to repeat code.

Restart current iteration in 'for' loop java

I have a for loop that asks the user to input a number and then does something with it 10 times
I want a check built in that, if the user enters a non accepted input, the loop should restart its current iteration
For example if the user enters something wrong in round 3, round 3 should be restarted.
How do i do that? is there something like a REDO statement in java?
something like this ?
for(int i=0; i<10; i++){
if(input wrong){
i=i-1;
}
}
You have a couple of choices here.
Continue
The continue statement in Java tells a loop to go back to its starting point. If you're using a for loop, however, this will continue on to the next iteration which is probably not what you want, so this works better with a while loop implementation:
int successfulTries = 0;
while(successfulTries < 10)
{
String s = getUserInput();
if(isInvalid(s))
continue;
successfulTries++;
}
Decrement
This approach seems ugly to me, but if you want to accomplish your task using a for loop, you can instead just decrement the counter in your for loop (essentially, 'redo') when you detect bad input.
for(int i = 0; i < 10; i++)
{
String s = getUserInput();
if(isInvalid(s))
{
i--;
continue;
}
}
I recommend you use a while loop.
Prefer avoiding to reassign the i variable, this may lead to confusion.
for(int i=0; i<10; i++){
String command = null;
do{
command = takeCommandFromInput();
} while(isNotValid(command));
process(command);
}

Categories

Resources