I have a for loop inside a while loop but it is not being reached
I am making a CPU scheduler for SJF, priority, and round robin. I need to make 6 processes with a random integer for the ID, priority and the burst time. I have a while loop set up to create 6 processes but it is not going into the for loop and then to my if statement to check if the current ID is already in my ArrayList of processes. I used the debugger to trace and follow the code and when it gets to the for loop it goes back to the start of the while loop. The bottom part after the while loop is for adding a 7th process and inputting the numbers for the process. It was working at some point, but then it decided to stop working. Thank you if you can help. I have been stuck on this for a couple days.
public static void main(String[] args) { ArrayList<Process> processes = new ArrayList<>(); Scanner input = new Scanner(System.in); while(processes.size() < 6){ int id = (int)(Math.random() * 10); int priority = (int)(Math.random() * 10); int burst_time = (int)((Math.random() * 80) + 20); Process p = new Process(id, priority, burst_time); for(int i = 0; i < processes.size(); i++){ if(p.getId() == processes.get(i).getId()) { break; } else { processes.add(p); } } } System.out.println("Enter a number between 1-10 for a new process."); int id = input.nextInt(); System.out.println("Now enter the priority number."); int priority = input.nextInt(); System.out.println("Enter in the burst time for the process."); int burst_time = input.nextInt(); Process pro = new Process(id,priority,burst_time); processes.add(pro); input.close(); }
Since processes
is empty when the while
loop starts, the body of the for
loop is never executed (the continuation condition for the for
loop is always false
) and nothing is never added to processes
. Hence, the while
loop never terminates, which is why the bottom part stopped working. (It is never reached.)
Reorganize your logic as follows:
while(processes.size() < 6){ int id = (int)(Math.random() * 10); int priority = (int)(Math.random() * 10); int burst_time = (int)((Math.random() * 80) + 20); Process p = new Process(id, priority, burst_time); boolean dup = false; for (int i = 0; !dup && i < processes.size(); i++){ dup = p.getId() == processes.get(i).getId(); } if (!dup) processes.add(p); }