LRU java,java.lang.IndexOutOfBoundsException
我只是看了太久,似乎无法解决索引越界异常。我忽略了什么?对于输入,我使用3帧,参考字符串的长度为20,数字为7,0,1,2,0,3,0,4,2,3,0,3,2,1,2,0,1,7,0,1。当堆栈返回时,最终结果应为107:LRU java,java.lang.IndexOutOfBoundsException,java,indexoutofboundsexception,lru,Java,Indexoutofboundsexception,Lru,我只是看了太久,似乎无法解决索引越界异常。我忽略了什么?对于输入,我使用3帧,参考字符串的长度为20,数字为7,0,1,2,0,3,0,4,2,3,0,3,2,1,2,0,1,7,0,1。当堆栈返回时,最终结果应为107: import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; public class LRU { public static void main(String[] ar
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class LRU {
public static void main(String[] args) throws IOException{
int numberOfFrames =0;
int numberOfFaults =0;
int referenceLength =0;
int stackSize=0;
Scanner scanner = new Scanner(System.in);
int lengthOfReference[];
ArrayList<Integer> stack = new ArrayList<Integer>();
System.out.println("Please enter a number of frames you would like to use");
numberOfFrames = scanner.nextInt();
System.out.println("Please enter the length of the reference string you would like to use");
referenceLength = scanner.nextInt();
lengthOfReference = new int[referenceLength];
for(int j=0; j< referenceLength; j++){
}
System.out.println("Please enter the reference string");
for(int i =0; i < referenceLength; i++){
lengthOfReference[i] = scanner.nextInt();
}
for(int i=0; i < referenceLength; i++){
//if stack contains the number, remove it and add it back in so it is the most recent used
if(stack.contains(lengthOfReference[i])){
stack.remove(lengthOfReference[i]);
stack.add(lengthOfReference[i]);
}
//if the stack is the same length as the number of frames, remove the last and add new reference string
else if(stackSize == numberOfFrames){
stack.remove(stack.size());
stack.add(lengthOfReference[i]);
numberOfFaults++;
}
//if the stack is less than the number of frames, just add the reference string in
else if(stack.size() < numberOfFrames){
stack.add(lengthOfReference[i]);
numberOfFaults++;
stackSize++;
}
}
System.out.println("Here is the final stack: ");
for(int i =0; i< numberOfFrames; i++){
System.out.println(stack.get(i));
}
System.out.println("Number of faults is: "+numberOfFaults);
}
}
import java.io.IOException;
导入java.util.ArrayList;
导入java.util.Scanner;
公共级LRU{
公共静态void main(字符串[]args)引发IOException{
int numberOfFrames=0;
int numberOfFaults=0;
int referenceLength=0;
int stackSize=0;
扫描仪=新的扫描仪(System.in);
int lengthofreeference[];
ArrayList堆栈=新的ArrayList();
System.out.println(“请输入您想要使用的帧数”);
numberOfFrames=scanner.nextInt();
System.out.println(“请输入要使用的引用字符串的长度”);
referenceLength=scanner.nextInt();
lengthofreeference=newint[referenceLength];
对于(int j=0;j
您的stack.remove(stack.size())是remove(int index),它需要0..n-1。
又一次滥用自动包装