-1

I've just been looking at this for too long and can't seem to resolve the index out of bounds exception. what am I overlooking? for the inputs i use 3 frames, a length of 20 for the reference string, and the numbers are 7,0,1,2,0,3,0,4,2,3,0,3,2,1,2,0,1,7,0,1. the end result should be 107 when the stack is returned:

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

}

}
Sollus
  • 11
  • 1
  • 6

1 Answers1

0

Your stack.remove(stack.size()) is remove(int index) which expects 0..n-1. Yet another autoboxing abuse.

user2023577
  • 1,752
  • 1
  • 12
  • 23