使用链接列表循环。输入不能超过一个进程

时间:2018-03-01 12:55:46

标签: java linked-list round-robin

图像显示存在逻辑错误。我只能输入一个流程。如果我添加更多,则会出现错误。系统说我有一个超出界限的阵列。我真的需要帮助解决这个问题。我将链表转换为数组的原因是因为我没有使用链表的任何专业知识。

here the output that i get

import java.util.*;

public class Test {



public static void main(String[] args) {

    Scanner sc= new Scanner(System.in);

LinkedList<Integer> cpuburst=new LinkedList<>();

LinkedList<Integer> priority=new LinkedList<>();

LinkedList<String> process=new LinkedList<>(); 

LinkedList<Integer> nextTime=new LinkedList<>();

int clockTime = 0;

double totalWaitTime = 0;

int quit,quantum=2;

int processesComplete = 0;
do{
  System.out.print("input process");

  process.add(sc.next());

  System.out.print("input cpu_burst");

   cpuburst.add(sc.nextInt());

  if (cpuburst.add(0)){

        processesComplete++;}

  System.out.print("input priority");

  priority.add(sc.nextInt());

  nextTime.add(0);

  System.out.print("more?");

  quit=sc.nextInt();

  }while (quit!=0);


  String[]Process=process.toArray(new String[process.size()]);

  Integer[]cpu_burst=cpuburst.toArray(new Integer [cpuburst.size()]);

  Integer[]Priority=priority.toArray(new Integer [priority.size()]);

  Integer[]next=nextTime.toArray(new Integer [nextTime.size()]);

    for (int i = 0; i < next.length; i++) {

        System.out.println(Process[i]+"\t\t"+cpu_burst[i]+"
  \t\t"+Priority[i]);

    }

 int roundRobinIndex = 0;

  System.out.println(" | Process | CPU Burst | Priority | Time  |  Clock        Time |  Wait Time |");

 while (processesComplete < cpu_burst.length){

 if (cpu_burst[roundRobinIndex] > 0){

     int time = Math.min(quantum, cpu_burst[roundRobinIndex]);// compare value 
        cpu_burst[roundRobinIndex] -= time;

        if (cpu_burst[roundRobinIndex] == 0)

            processesComplete++;

        int waitTime = clockTime - next[roundRobinIndex];

        totalWaitTime += waitTime;

          System.out.println(" |    " + Process[roundRobinIndex] + "    |    " + cpu_burst[roundRobinIndex]
                + "      |    " + Priority[roundRobinIndex] + "     |    " + time + "  |     " + clockTime
                + "        | " + waitTime + "   |");

        //clockTime += quantum;

        clockTime += time;
        next[roundRobinIndex] = clockTime           
 }
  roundRobinIndex = (roundRobinIndex + 1)% cpu_burst.length;
}       System.out.println("Average wait time"+totalWaitTime/cpu_burst.length);          
}  
}

1 个答案:

答案 0 :(得分:1)

好吧,我认为此代码存在一些问题,但要回答这个问题:您收到IndexOutOfBounds错误,因为每次添加进程时,都会调用

if (cpuburst.add(0)){

    processesComplete++;}

您正在向cpuburst列表中添加一个附加项(值0),因此该列表的长度是其他项的两倍,在输入值和零之间交替。后来,你写了

  if (cpu_burst[roundRobinIndex] > 0) {
     //...some code here...
  }
  roundRobinIndex = (roundRobinIndex + 1) % cpu_burst.length;

这意味着,当用户输入了一个cpuburst值时,第一次执行的代码就会被执行,然后下一次因为“零”和“第三”而获胜。时间(当您使用两个进程进行测试时),它将再次输入if子句,但您会在

处获得indexOutOfBounds错误
            int waitTime = clockTime - next[roundRobinIndex];

因为接下来只有两个条目。