Question

Hello everyone. I have a bankers algorithm written in java that gets inputs from a .txt...

Hello everyone. I have a bankers algorithm written in java that gets inputs from a .txt file. The file has 7 processes and 5 resources however, when the program runs, it doesn't sum the resource columns correctly. The program runs correctly for smaller matricies (4 processes, 3 resources), not sure what the issue is and have been looking over the code for awhile so maybe another set of eyes would help...thanks

BankersAlgorithm.java

/**
 * This program implements Bankers algorithm which will determine whether
 * the state of the system that is read in from a file is safe or unsafe
 * and output the result back to the user.
 */
// import the java packages
import java.io.*;
import java.util.StringTokenizer;
import java.util.Scanner;
// create a class name bankerAlgorithm

public class BankersAlgorithm
{
//main method
    public static void main(String[]args)throws IOException,FileNotFoundException, NullPointerException
 {
//Declare local variables
        int n = 0; // Variable to hold the number of processes
        int m = 0; // Variable to hold the number of resources
        int count = 0; // Counter that holds the number of lines in the file
        int lineCount = 0; // Counter that holds the number of lines in each matrix
        int [] sumColumn; // Array holding the value of the sum of each column.
        int [] sumRow; // Array holding the value of the sum of each row.
        int [] resourceVector; // Array that holds the resource vector
        int [] availableVector; // Array that holds the available vector
        int [] work; // Array that holds the currently available vector
        int [] processSequence; // Array holding the sequence of processes to run to completion
        int index = 0; // Integer for holding the index value of the process sequence
        boolean finish[]; // Boolean array that tells if a process has finished
        int [][] claimMatrix; // Array that holds the claim matrix
        int [][] allocationMatrix; // Array that holds the allocation matrix
        int [][] needMatrix; // Array that holds the need matrix ( C-A );
        boolean isSafe = false; // Boolean value that tells if the system is in a safe or unsafe state

// Variables to read in line from a file and tokenize
        String line;
        String fileIn;
        File file = new File("FILE PATH");
        StringTokenizer tokens;
        @SuppressWarnings("resource")
        Scanner input = new Scanner(System.in);
        //System.out.print("Please enter in the name of the file : "); 
        //fileIn = input.nextLine(); WILL ALLOW FOR MANUAL INPUT OF FILE
       // build input stream
        FileReader fr = new FileReader(file); //or fileIn
      // Use Buffered reader to read one line at a time
        BufferedReader bufRead = new BufferedReader(fr);
// Read first line
        line = bufRead.readLine();
        n = Integer.parseInt(line);
// Read the second line
        line = bufRead.readLine();
        m = Integer.parseInt(line);
//Create 2D array for each of the m process and n resources
        claimMatrix = new int[n][m];
        allocationMatrix = new int[n][m];
        needMatrix = new int [n][m];
//Create resourceVector
        resourceVector = new int[m];
//Create availableVector
        availableVector = new int[m];
        work = new int[m];
        finish = new boolean[n];
        processSequence = new int[n];
        sumColumn = new int[m];
        sumRow = new int[n];
        line = bufRead.readLine();
        count++;

// Read the file and get the claimMatrix from the file
        while(line != null && lineCount < n)
        {
            tokens = new StringTokenizer(line);
            if(tokens.hasMoreTokens())
            {
                for(int j = 0; j < m; j++)
                {
                    claimMatrix[lineCount][j]=Integer.parseInt(tokens.nextToken());
                }
            }
            line = bufRead.readLine();
            lineCount++;
            count++;
        }
        lineCount = 0;
// Read the file and get the Allocation Matrix
        while(line != null && lineCount < n)
        {
            tokens = new StringTokenizer(line);
            if(tokens.hasMoreTokens())
            {
                for(int j = 0; j < m; j++)
                {
                    allocationMatrix[lineCount][j] = Integer.parseInt(tokens.nextToken());
                }
            }
            line = bufRead.readLine();
            lineCount++;
            count++;
        }
// Read the last line and set Resource Vector
        try{
       tokens = new StringTokenizer(line);
        while(tokens.hasMoreTokens())
        {
            for(int i = 0; i < m; i++)
            {
                resourceVector[i] = Integer.parseInt(tokens.nextToken());
            }
        }
       }catch (NullPointerException e){
           e.printStackTrace();
       }

// Cloe the bufferedreader and file
        bufRead.close();
        fr.close();
// Determine the initial need matrix
        for(int i = 0; i < n; i++)
        {
            for(int j = 0; j < m; j++)
            {
                needMatrix[i][j] = claimMatrix[i][j]- allocationMatrix[i][j];
            }
        }
// Determine the initial available vector
        for(int i = 0; i < n; i++)
        {
            for(int j = 0; j < m; j++)
            {

               sumColumn[j] += allocationMatrix[i][j];
                sumRow[i] += needMatrix[i][j];
            }
        }
        for(int j = 0; j < m; j++)
        {
            availableVector[j] = resourceVector[j] - sumColumn[j];
        }
// Initialize Work and Finish
        for(int j = 0; j < m; j++)
        {
            work[j]=availableVector[j];
        }
        for(int i = 0; i < n; i++)
        {
            finish[i] = false;
        }
// Safety Algorithm (checks if the system is in a safe or found state)
        boolean found = false;
        do
        {
// Process found flag
            found = false;
            int i = 0;
            for(; i < n; i++)
            {
                if ((!finish[i]))
                {
                    boolean good = true;
                    for (int j = 0; j < m; j++)
                    {
// If the need is greater than the available,
//then the process is not able to run to completion
// So it is not good
                        if(needMatrix[i][j] > work[j])
                        {
                            good = false;
                            break;
                        }
                    }
// Try another process
                    if (!good)
                        continue;
                    found = true;
                    break;
                }
            }
// Process is found that can run to completion, simulate execution
            if(found)
            {
                finish[i] = true;
                for (int j = 0; j < m; j++)
                {
                    work[j] += allocationMatrix[i][j];
                }
                processSequence[index++] = i;
            }
        }while (found);
//check whether all process are finished or not
        for(int i = 0; i < n; i++)
        {
            if(!finish[i])
            {
                isSafe = false;
            }
            else
            {
                isSafe = true;
            }
        }
// Display output
        System.out.println("Number of Processes : " + n);
        System.out.println("Number of Resources : " + m + "\n");

//Display the claimMatrix
        System.out.println("claimMatrix : ");
        for(int i = 0; i < n; i++)
        {
            for(int j = 0; j < m; j++)
            {
                System.out.print(claimMatrix[i][j] + " ");
            }
            System.out.println();
        }
//Display allocation matrix
        System.out.println("\nAllocation Matrix : ");
        for(int i = 0; i < n; i++)
        {
            for(int j = 0; j < m; j++)
            {
                System.out.print(allocationMatrix[i][j] + " ");
            }
            System.out.println();
        }
//Display resource matrix
        System.out.println("\nResource Vector : ");
        for(int i = 0; i < m; i++)
        {
            System.out.print(resourceVector[i] + " ");
        }
        System.out.println();
//Display the Need matrix
        System.out.println("\nNeed Matrix : ");
        for(int i = 0; i < n; i++)
        {
            for(int j = 0; j < m; j++)
            {
                System.out.print(needMatrix[i][j] + " ");
            }
            System.out.println();
        }
//Display the Available Vector
        System.out.println();
        System.out.println("Initial Available Vector : ");
        for(int j = 0; j < m; j++)
        {
            System.out.print(availableVector[j] +" ");
        }
        System.out.println("\n");
//Print the output
        if(isSafe)
        {
            System.out.print("Process Sequence : ");
            for(int i = 0; i < processSequence.length; i++)
            {
                System.out.print((processSequence[i]+1) + " ");
            }
            System.out.println();
            System.out.println("This system is in a safe state!!!");
        }
        else
        {
            System.out.println("This system is not in a safe state!!!");
        }
    }
}

bankers.txt

7
5
1 1 2 3 5
3 2 4 4 6
2 2 2 2 2
0 0 0 0 5
1 3 6 7 6
2 2 2 0 0
1 0 0 0 1
0 1 2 3 4
2 0 3 4 6
1 2 0 0 0
0 0 0 0 4
1 3 4 7 5
2 1 2 0 0
0 0 0 0 1

OUTPUT

"C:\Program Files\Java\jdk-9.0.4\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2018.1.3\lib\idea_rt.jar=64246:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2018.1.3\bin" -Dfile.encoding=UTF-8 -classpath C:\Users\andre\OneDrive\Documents\CMSC412\out\production\CMSC412 BankersAlgorithm

java.lang.NullPointerException

at java.base/java.util.StringTokenizer.<init>(StringTokenizer.java:199)

at java.base/java.util.StringTokenizer.<init>(StringTokenizer.java:236)

at BankersAlgorithm.main(BankersAlgorithm.java:202)

Number of Processes : 7

Number of Resources : 5

claimMatrix :

1 1 2 3 5

3 2 4 4 6

2 2 2 2 2

0 0 0 0 5

1 3 6 7 6

2 2 2 0 0

1 0 0 0 1

Allocation Matrix :

0 1 2 3 4

2 0 3 4 6

1 2 0 0 0

0 0 0 0 4

1 3 4 7 5

2 1 2 0 0

0 0 0 0 1

Resource Vector :

0 0 0 0 0

Need Matrix :

1 0 0 0 1

1 2 1 0 0

1 0 2 2 2

0 0 0 0 1

0 0 2 0 1

0 1 0 0 0

1 0 0 0 0

Initial Available Vector :

-6 -7 -11 -14 -20

This system is not in a safe state!!!

Process finished with exit code 0

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Program code to copy:

/**

* This program implements Bankers algorithm which will determine whether

* the state of the system that is read in from a file is safe or unsafe

* and output the result back to the user.

*/

// import the java packages

import java.io.*;

import java.util.StringTokenizer;

import java.util.Scanner;

// create a class name bankerAlgorithm

public class BankerAlgorithm

{

//main method

public static void main(String[]args)throws IOException,FileNotFoundException

{

//Declare local variables

int n = 0; // Variable to hold the number of processes

int m = 0; // Variable to hold the number of resources

int count = 0; // Counter that holds the number of lines in the file

int lineCount = 0; // Counter that holds the number of lines in each matrix

int [] sumColumn; // Array holding the value of the sum of each column.

int [] sumRow; // Array holding the value of the sum of each row.

int [] resourceVector; // Array that holds the resource vector

int [] availableVector; // Array that holds the available vector

int [] work; // Array that holds the currently available vector

int [] processSequence; // Array holding the sequence of processes to run to completion

int index = 0; // Integer for holding the index value of the process sequence

boolean finish[]; // Boolean array that tells if a process has finished

int [][] claimMatrix; // Array that holds the claim matrix

int [][] allocationMatrix; // Array that holds the allocation matrix

int [][] needMatrix; // Array that holds the need matrix ( C-A );

boolean isSafe = false; // Boolean value that tells if the system is in a safe or unsafe state

  

// Variables to read in line from a file and tokenize

String line;

String fileln;

StringTokenizer tokens;

@SuppressWarnings("resource")

Scanner input = new Scanner(System.in);

System.out.print("Please enter in the name of the file : ");

fileln = input.nextLine();

// build input stream

FileReader fr = new FileReader(fileln);

// Use Buffered reader to read one line at a time

BufferedReader bufRead = new BufferedReader(fr);

// Read first line

line = bufRead.readLine();

n = Integer.parseInt(line);

// Read the second line

line = bufRead.readLine();

m = Integer.parseInt(line);

//Create 2D array for each of the m process and n resources

claimMatrix = new int[n][m];

allocationMatrix = new int[n][m];

needMatrix = new int [n][m];

//Create resourceVector

resourceVector = new int[m];

//Create availableVector

availableVector = new int[m];

work = new int[m];

finish = new boolean[n];

processSequence = new int[n];

sumColumn = new int[m];

sumRow = new int[n];

line = bufRead.readLine();

  

count++;

// Read the file and get the claimMatrix from the file

while(line != null && lineCount < n)

{

tokens = new StringTokenizer(line);

if(tokens.hasMoreTokens())

{

for(int j = 0; j < m; j++)

{

claimMatrix[lineCount][j]=Integer.parseInt(tokens.nextToken());  

}  

}  

line = bufRead.readLine();

lineCount++;

count++;

}

lineCount = 0;

// Read the file and get the Allocation Matrix

while(line != null && lineCount < n)

{

tokens = new StringTokenizer(line);

if(tokens.hasMoreTokens())

{

for(int j = 0; j < m; j++)

{

allocationMatrix[lineCount][j] = Integer.parseInt(tokens.nextToken());

}

}

line = bufRead.readLine();

lineCount++;

count++;

}  

// Read the last line and set Resource Vector

tokens = new StringTokenizer(line);

while(tokens.hasMoreTokens())

{

for(int i = 0; i < m; i++)

{

resourceVector[i] = Integer.parseInt(tokens.nextToken());

}

}  

// Close the bufferreader and file

bufRead.close();

fr.close();

// Determine the initial need matrix

for(int i = 0; i < n; i++)

{

for(int j = 0; j < m; j++)

{

needMatrix[i][j] = claimMatrix[i][j]- allocationMatrix[i][j];

}

}  

// Determine the initial available vector

for(int i = 0; i < n; i++)

{

for(int j = 0; j < m; j++)

{

sumColumn[j] += allocationMatrix[i][j];

sumRow[i] += needMatrix[i][j];

}

}

for(int j = 0; j < m; j++)

{

availableVector[j] = resourceVector[j] - sumColumn[j];

}

// Initialize Work and Finish

for(int j = 0; j < m; j++)

{

work[j]=availableVector[j];

}

for(int i = 0; i < n; i++)

{

finish[i] = false;

}

// Safety Algorithm (checks if the system is in a safe or found state)

boolean found = false;

do

{

// Process found flag

found = false;

int i = 0;

for(; i < n; i++)

{

if ((!finish[i]))

{

boolean good = true;  

for (int j = 0; j < m; j++)

{  

// If the need is greater than the available,

//then the process is not able to run to completion

// So it is not good  

if(needMatrix[i][j] > work[j])

{

good = false;

break;

}

}

// Try another process

if (!good)

continue;

found = true;

break;  

}

}

// Process is found that can run to completion, simulate execution

if(found)  

{

finish[i] = true;

for (int j = 0; j < m; j++)

{  

work[j] += allocationMatrix[i][j];

}

processSequence[index++] = i;

}

}while (found);

//check whether all process are finished or not

for(int i = 0; i < n; i++)

{

if(!finish[i])

{

isSafe = false;

}

else

{

isSafe = true;

}

}

// Display output

System.out.println("Number of Processes : " + n);

System.out.println("Number of Resources : " + m + "\n");

  

//Display the claimMatrix

System.out.println("claimMatrix : ");

for(int i = 0; i < n; i++)

{

for(int j = 0; j < m; j++)

{

System.out.print(claimMatrix[i][j] + " ");

}

System.out.println();

}

//Display allocation matrix

System.out.println("\nAllocation Matrix : ");

for(int i = 0; i < n; i++)

{

for(int j = 0; j < m; j++)

{

System.out.print(allocationMatrix[i][j] + " ");

}

System.out.println();

}

//Display resource matrix

System.out.println("\nResource Vector : ");

for(int i = 0; i < m; i++)

{

System.out.print(resourceVector[i] + " ");

}

System.out.println();

//Display the Need matrix

System.out.println("\nNeed Matrix : ");

for(int i = 0; i < n; i++)

{

for(int j = 0; j < m; j++)

{

System.out.print(needMatrix[i][j] + " ");

}

System.out.println();

}

//Display the Available Vector

System.out.println();

System.out.println("Initial Available Vector : ");

for(int j = 0; j < m; j++)

{

System.out.print(availableVector[j] +" ");

}

System.out.println("\n");

//Print the output

if(isSafe)

{

System.out.print("Process Sequence : ");

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

{

System.out.print((processSequence[i]+1) + " ");

}

System.out.println();

System.out.println("This system is in a safe state!!!");

}

else

{

System.out.println("This system is not in a safe state!!!");

}

}  

}

Program code screen shot:

*This program implements Bankers algorithm which will determine whether * the state of the system that is read in from a file is safe or unsafe * and output the result back to the user / import the java packages import java.io.* import java.util.StringTokenizer; import java.util.Sca nneri // create a class name bankerAlgorithm public class BankerAlgorithnm //main method public static void main (String[]args) throws IOException, FileNotFoundException //Declare local variables int n0 1/Variable to hold the number of processes int m 0 I/ Variable to hold the number of resources int count-0 // Counter that holds the number of lines in the //file int lineCount-0: // Counter that holds the number of lines in int sumColumn: 1/ Array holding the value of the sum of each int sumRow; // Array holding the value of the sum of each //each matrix //column //row. int [ resourceVectori 1/ Array that holds the resource vector int availableVectori II Array that holds the available vector int worki // Array that holds the currently available vector int [ processSequence: 1/ Array holding the sequence of //processes to run to completion int index-0 // Integer for holding the index value of the //process sequence boolean finish[ // Boolean array that tells if a process has //finished int [] claimMatrix: // Array that holds the claim matrix int [)] allocationMatrix: 1/ Array that holds the allocation //matrix int [)] needMatrix; // Array that holds the need matrix C-A boolean isSafe = false; // Boolean value that tells if the //system is in a safe or unsafe state /Variables to read in line from a file and tokenize String line: String fileln: StringTokenizer tokens; @SuppressWarnings(resource)

Add a comment
Know the answer?
Add Answer to:
Hello everyone. I have a bankers algorithm written in java that gets inputs from a .txt...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Coding Requirements for Assignment2_1.java: Based on Assignment1.java, re-do all 7 methods from triangle_0 to triangle_6 by...

    Coding Requirements for Assignment2_1.java: Based on Assignment1.java, re-do all 7 methods from triangle_0 to triangle_6 by storing characters (which could be symbols or digits) in a 2D "square" array, meaning it has equal number of rows and columns. Now, because each triangle is supposed to contain rows filled with different number of characters, you are required to fill each row with only required number of characters in this square array. For example, in an up-side-down 8-row triangle of "$", the...

  • I have a Graph.java which I need to complete four methods in the java file: completeGraph(),...

    I have a Graph.java which I need to complete four methods in the java file: completeGraph(), valence(int vid), DFS(int start), and findPathBFS(int start, int end). I also have a JUnit test file GraphTest.java for you to check your code. Here is Graph.java: import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; import java.util.Stack; /* Generic vertex class */ class Vertex<T> { public T data; public boolean visited; public Vertex() { data = null; visited = false; } public Vertex(T _data) { data =...

  • Java Im doing a binary search on an array and need to allow as many queries...

    Java Im doing a binary search on an array and need to allow as many queries as possible and cannot figure out how to. The output should read something like this. Enter a number. 3 3 is a prime number. Enter another number. 4 4 is not a prime number. Enter another number. 8 Current file not large enough for 8. Enter another number. -1 Bye. My code so far looks like this. public static void main(String[] args)    {...

  • Hello this is my java sorting algorithm program i need all of my errors corrected so...

    Hello this is my java sorting algorithm program i need all of my errors corrected so I can run it. thank you!! import java.util.Scanner;    public class SortingAlogs { public static void main(String[]args){ int array [] = {9,11,15,34,1}; Scanner KB = new Scanner(System.in); int ch; while (true) { System.out.println("1 Bubble sort\n2 Insertion sort\n3 Selection sort\n"); ch = KB.nextInt(); if (ch==1)    bubbleSort(array); if (ch==2)    insertion(array); if (ch==3)    Selection(array); if (ch==4) break;    print(array);    System.out.println(); }    }...

  • I have a multithreaded java sorting program that works as follows: 1. A list of double...

    I have a multithreaded java sorting program that works as follows: 1. A list of double values is divided into two smaller lists of equal size 2. Two separate threads (which we will term sorting threads) sort each sublist using a sorting algorithm of your choice 3. The two sublists are then merged by a third thread merging thread that merges the two sublists into a single sorted list. SIMPLE EXECUTION >java SortParallel 1000 Sorting is done in 8.172561ms when...

  • need help editing or rewriting java code, I have this program running that creates random numbers...

    need help editing or rewriting java code, I have this program running that creates random numbers and finds min, max, median ect. from a group of numbers,array. I need to use a data class and a constructor to run the code instead of how I have it written right now. this is an example of what i'm being asked for. This is my code: import java.util.Random; import java.util.Scanner; public class RandomArray { // method to find the minimum number in...

  • Make the Sudoku algorithm for checking for duplicates to be Big -O of N, instead of...

    Make the Sudoku algorithm for checking for duplicates to be Big -O of N, instead of N-squared. I.E. No nested for loops in rowIsLatin and colIsLatin. Only nested loop allowed in goodSubsquare. public class Sudoku {               public String[][] makeSudoku(String s) {              int SIZE = 9;              int k = 0;              String[][] x = new String[SIZE][SIZE];              for (int i = 0; i < SIZE; i++) {                     for (int j = 0; j < SIZE; j++)...

  • composed the following java code to read a string from a text file but receiving compiling...

    composed the following java code to read a string from a text file but receiving compiling errors. The text file is MyNumData.txt. Included the original java script that generated the output file. Shown also in the required output results after running the java program. I can't seem to search for the string and output the results. Any assistance will be greatly appreciated. import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; public class Main {   public static void main(String[] args) {     System.out.print("Enter the...

  • This is a java homework for my java class. Write a program to perform statistical analysis...

    This is a java homework for my java class. Write a program to perform statistical analysis of scores for a class of students.The class may have up to 40 students.There are five quizzes during the term. Each student is identified by a four-digit student ID number. The program is to print the student scores and calculate and print the statistics for each quiz. The output is in the same order as the input; no sorting is needed. The input is...

  • Why is my multiplication wrong when i do a matrix of 3 x 5 and 2...

    Why is my multiplication wrong when i do a matrix of 3 x 5 and 2 x 2? code below import java.util.*; public class matrix { public static void main(String[] args) { int m, n, i, j; Random rand = new Random(); Scanner scan = new Scanner(System.in); System.out.print("enter how many rows:"); m = scan.nextInt(); System.out.print("enter how many columns:"); n=scan.nextInt(); int matrix_1[][] = new int[m][n]; //Initialize matrixes int maritx_2[][] = new int[m][n]; int matrix_add[][] = new int[m][n]; int matrix_mul[][] = new...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT