gpt4 book ai didi

java - 使用链表进行循环。输入不能使用多个进程

转载 作者:行者123 更新时间:2023-12-02 11:34:31 24 4
gpt4 key购买 nike

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

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);
}
}

最佳答案

嗯,我认为这段代码有几个问题,但要回答这个问题:您会收到 IndexOutOfBounds 错误,因为每次添加进程时,当您调用

if (cpuburst.add(0)) {
processesComplete++;
}

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

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

这意味着,当用户输入一个 cpuburst 值时,其中的代码将在第一次执行,然后下一次不会执行,因为有一个零,第三次(当您使用两个进程进行测试时) ),它会再次进入 if 子句,但你会在

处收到 indexOutOfBounds 错误
int waitTime = clockTime - next[roundRobinIndex];

因为 next 只有两个条目。

关于java - 使用链表进行循环。输入不能使用多个进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49050202/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com