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

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.

Related

Variable in for loop is giving a message that "The value of the local variable i is not used"

I wrote a for loop that is supposed to determine if there is user input. If there is, it sets the 6 elements of int[] valueArr to the input, a vararg int[] statValue. If there is no input, it sets all elements equal to -1.
if (statValue.length == 6) {
for (int i = 0; i < 6; i++) {
valueArr[i] = statValue[i];
}
} else {
for (int i : valueArr) {
i = -1;
}
}
I am using Visual Studio Code, and it is giving me a message in for (int i : valueArr) :
"The value of the local variable i is not used."
That particular for loop syntax is still new to me, so I may be very well blind, but it was working in another file:
for(int i : rollResults) {
sum = sum + i;
}
I feel that I should also mention that the for loop giving me trouble is in a private void method. I'm still fairly new and just recently started using private methods. I noticed the method would give the same message when not used elsewhere, but I do not see why it would appear here.
I tried closing and reopening Visual Studio Code, deleting and retyping the code, and other forms of that. In my short experience, I've had times where I received errors and messages that should not be there and fixed them with what I mentioned, but none of that worked here.
for (int i : valueArr) {
.... CODE HERE ...
}
This sets up a loop which will run CODE HERE a certain number of times. Inside this loop, at the start of every loop, an entirely new variable is created named i, containing one of the values in valueArr. Once the loop ends this variable is destroyed. Notably, i is not directly the value in valueArr - modifying it does nothing - other than affect this one loop if you use i later in within the block. It does not modify the contents of valueArr.
Hence why you get the warning: i = -1 does nothing - you change what i is, and then the loop ends, which means i goes away and your code hasn't changed anything or done anything, which surely you didn't intend. Hence, warning.
It's not entirely clear what you want to do here. If you intend to set all values in valueArr to -1, you want:
for (int i = 0; i < valueArr.length; i++) valueArr[i] = -1;
Or, actually, you can do that more simply:
Arrays.fill(valueArr, -1);
valueArr[i] = -1 changes the value of the i-th value in the valueArr array to -1. for (int i : valueArr) i = -1; does nothing.

java- How do I create a String check with a delay of a certain amount of time?

I am learning java and so far I have created a password check using if statements. However I inserted my working String check into a while loop and added Thread.sleep(3000); for a 3 second delay, however once I completed that my GUI just keeps lagging and freezing on one page as if the button was pressed. Can somebody please show me how to make a working example of a code with a String check and after a certain amount of tries a delay to stop the user from trying again?
(here is what I have:)
//var declaration
boolean match = false;
String1 = "hi";
String2 = (I know this is not code but just to omit some code:) userInput
int time = 3000;
int attempt = 0;
//check
while(!match && attempt < (maximumTries+1)){
if(String1.equals(String2)){
System.out.print("match");
}
else if(attempt < 11){
attempt++;
System.out.println("Failed:" + attempt);
}
else{
attempt++;
System.out.println("Please try again later you have:" + attempt + "failed attempts");
try{
Thread.sleep(time);
}
catch(InterruptedException ex) {
Logger.getLogger(PasswordEntry.class.getName()).log(Level.SEVERE, null, ex);
}
time = time + 1000;//1 second more every time
}
}
your code is doing an infinite loop once the first attempt does not match.
in each of the iterations of your loop there is no change at all, aside from incrementing the counter. so the counter just increases forever (with some delays in between).
it seems the reasoning behind your code was that String2 got updated with user input inside the loop not outside. This way, on each iteration you would have a different String2 to compare against.
That's your issue, not the way you delay between attempts (that for sure can be improved in any case).
You should avoid using the Thread.sleep option since it completely freezes the main thread. You could also try creating another thread, which will be frozen and later in gives a callback to the main one. For example through a boolean variable. I'd also agree on the timer solution mentioned by BladeMight.

Infinite while loop, can't understand why

I've started learning programming just recently at my university, so far we are battling with Java. Our task is to do a simulation of different processor algorithms like fcfs, sjf etc. I've tried many approaches and the one you see below is probably the least optimized. I'm aware, that this code might not be the greatest, as well as algorithm itself, but I wanted to see if it work as intended and I found a problem, that I can't really understand for a little too long and I won't be able to sleep until I find out what is wrong with it.
In the code below you will find a while loop with comment line "Why is this loop inifnite" written in caps. I have no idea why it never stops (I ran some printing tests and I know that this is the loop that is going on forever) and it is really getting on my nerves (most likely because the solution is really easy now).
Some explanation: I create a list of processes, that I then execute some methods on. Process is described by: execution time (execTime); time, that it needed to wait to start getting executed (waitTime); at what time it is ready to be executed (inTime) (but might be waiting for other process to finish executing) and id. I execute process by reducing it's execTime until it reaches 0, then I remove the process and do the same for "new first one". And this reducing part is when the program go to infinity.
Mango
import java.util.ArrayList;
import java.util.List;
public class Processor {
List<Process> listOP = new ArrayList<Process>();
int processorTime = 0;
int totalWaitTime = 0;
int numberOfProcesses = 0;
public Processor(){
for(int i=0; i<100; i++){
listOP.add(new Process(i));
if(i>0)
listOP.get(i).inTime += listOP.get(i-1).inTime + (int)((Math.random() + 0.1)*10);
System.out.println("Proces " + (listOP.get(i).id + 1) + " czas wejścia " + listOP.get(i).inTime);
}
}
public double fcfs(){
numberOfProcesses = listOP.size();
while(listOP.size() != 0){
if(listOP.get(0).inTime > processorTime){
for(int i=0; i<listOP.size(); i++){
listOP.get(i).waitTime = 0;
}
}
totalWaitTime += listOP.get(0).waitTime;
while(listOP.get(0).execTime != 0){//**WHY IS THIS LOOP INFINITE**
for(int i=1; i<listOP.size(); i++){
if(processorTime == listOP.get(i).inTime)
listOP.get(i).waitTime++;
}
listOP.get(0).execTime--;
processorTime++;
}
processorTime++;
listOP.remove(0);
}
System.out.println(totalWaitTime);
System.out.println(numberOfProcesses);
System.out.println(processorTime);
System.out.println("Średni czas tego ciągu procesów: " + totalWaitTime/numberOfProcesses);
return totalWaitTime/numberOfProcesses;
}
}

Java Bubble Sort Iterates Only Twice

I'm in an intro to Java course and am just trying to get ahead of the curve with some practice, so I'm making a bubble sort program. For some reason, it only will run through the outer loop twice.
public ArrayList SortArray(ArrayList<Integer> u) {
int temp;
int spot;
for (int isOrdered = 1; isOrdered == 1;) {
for (spot = 0; spot < u.size() - 1; spot ++) {
System.out.println(u.get(spot) + " " + u.get(spot + 1) + " " + spot);
if (u.get(spot) > u.get(spot + 1)) {
temp = u.get(spot + 1);
u.set(spot + 1, u.get(spot));
u.set(spot, temp);
isOrdered = 1;
}
else {
isOrdered = 0;
}
}
}
return u;
}
As far as I can tell, what's happening is after the second iteration, it doesn't reset 'spot' to 0 so it doesn't run through the loop again. Any ideas?
Well, for starters that's an ... unusual way of using a for loop to implement a while loop. Try using a boolean for isOrdered and a while(!isOrdered) for a statement like that.
As Ted Hopp's comment said, your logic isn't quite right. What your code is doing is that it will sort ONE value in the list and once that value has "bubbled up" your flag is set to true.
You need your outer loop's condition to be that it keeps running until ALL cells are in order.
Right now your flag simply says it's sorted, when you've gone through the list, but what it needs to do is be true when it's gone through the list without performing a swap.
Try to implement that without looking, then if you can't get it (I'm assuming you're interested in doing it yourself since you're working ahead in your class) take a look at the sample here.

Java: perform for statement until given variable has reached a certain value?

I want to have a for statement that repeats until a given int reaches a certain value.
For example...
for (int variable = 0; variable < other_variable; variable++) {
The problem with this is that the for statement will never end. It will continue to repeat endlessly. What have I done wrong?
This is my code...
boolean itemexist_check = false;
do {
int i2 = m_area.m_items.size();
for (int i = 0; i < i2; i++) {
String s2 = m_area.m_items.get(i).returnName();
System.out.println("Checking...");
if (s2.contains(s)) {
System.out.println("You take the " + s2 + ".");
itemexist_check = true;
player.addItem(m_area.m_items.get(i));
m_area.m_items.remove(i);
}
else {
//do nothing, repeat loop
}
}
}
while (itemexist_check == false);
In this code, m_area.m_items.size() would return 1, so i2 would be 1.
There are several possibilities:
you change variable inside the body of the loop;
you change other_variable inside the body of the loop;
other_variable is set to a large value, in which case the loop might take a long time to terminate;
your code never completes a certain iteration of the loop, for example:
it's getting stuck inside a nested loop as suggested by #Eng.Fouad in the comments, or
it's waiting for a lock, or
it's blocking inside an I/O call that never completes (or takes a long time to complete) etc.
Without knowing the typical value of other_variable and seeing the body of the loop it's anyone's guess.
On a side note,
String s2 = m_area.m_items.get(i).returnName();
is going to cause an exception if invoked in a subsequent or later repetition after
m_area.m_items.remove(i);
is invoked, because every time m_area.m_items.remove(i) is invoked, the list/array loses an item and its size reduces, which is never reflected in the iteration boundary check.
Surely it is the do/while loop that isn't terminating? That for loop cannot possibly run forever.
You should try a
do {
}while(condition is true)
loop. However that said, you have to implement checks assuming that there will be runaway data or conditions resulting in an infinite loop. Just my 2 cents

Categories

Resources