Question

Java: Hello, can someone please find a way to call my arraylist "list" and linkedhashmap called...

Java: Hello, can someone please find a way to call my arraylist "list" and linkedhashmap called "jobMap" in my main method instead of calling them in the 2 classes? Also, is there a way to avoid the "Suppress Warning" portion in RoundRobin.java? I haven't been able to find a way for some reason. This is a job scheduling program, so the output should give the same values. To run: javac Main.java, java Main 5jobs.txt . txt file will be provided below.

______________________________________________________________________________________________________________________________

Main.java

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.Scanner;

public class Main{
public static void main(String[] args) throws IOException{

int time;
float turnaround;

Scanner scan = new Scanner(new File(args[0]));

// linkedhashmap used to maintain order jobs are read
LinkedHashMap jobs = new LinkedHashMap();

// reads each value, first the string (job title), then its value (time)
while(scan.hasNextLine()){
jobs.put(scan.nextLine(), Integer.parseInt(scan.nextLine()));
}

// checks for an empty file
if(jobs.isEmpty()){
System.out.println("ERROR: File is empty. Please try again.");
System.exit(0);
}

ShortestJobFirst sjf = new ShortestJobFirst();
RoundRobin rr = new RoundRobin();


sjf.shortestJobFirst(jobs, 0, 0);
rr.roundRobin(jobs, 0, 0, 2);
rr.roundRobin(jobs, 0, 0, 5);   
}

}

______________________________________________________________________________________________________________________________

ShortestJobFirst.java:

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class ShortestJobFirst{
public static void shortestJobFirst(LinkedHashMap jobs, int time, float turnaround){

System.out.println("Shortest-Job-First (SJF): \n");
System.out.println("Job\t\tStart Time\tEnd Time\tJob Description\n");

// specific method that sorts linkedhashmap by values in ascending order
LinkedHashMap jobMap = jobs.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));

// displaying start times, calculating end time
for (String job : jobMap.keySet()){
System.out.print(job + "\t\t" + time + "\t\t");
time += jobs.get(job);
turnaround += time;
System.out.println(time + "\t\t" + job + " completed at time " + time);
}

// displaying average turnaround time
System.out.print("\nAverage turnaround time (SJF): ");
System.out.printf("%.2f / %d = %.2f", turnaround, jobs.keySet().size(), (turnaround/ jobs.keySet().size()));
System.out.println("\n**********************************************************************");
}

}

________________________________________________________________________________________________________________________________

RoundRobin.java

import java.util.ArrayList;
import java.util.LinkedHashMap;

public class RoundRobin{
@SuppressWarnings("unchecked")
public static void roundRobin(LinkedHashMap jobs, int time, float turnaround, int time_slice){

LinkedHashMap jobMap = (LinkedHashMap)jobs.clone();
ArrayList list = new ArrayList();


for (String job : jobs.keySet()) list.add(job);
   System.out.println("Round Robin with time slice = " + time_slice);
   System.out.println("Job\t\tStart Time\tEnd Time\tJob Description");

while (!list.isEmpty()) {

String job = (String)list.remove(0);
System.out.print(job + "\t\t" + time + "\t\t");

if ((Integer)jobMap.get(job) <= time_slice) {
time += (Integer)jobMap.get(job);
turnaround += time;
jobMap.put(job, 0);
System.out.println(time + "\t\t" + job + " completed at time " + time);
}else{
time += time_slice;
jobMap.put(job, (Integer)jobMap.get(job) - time_slice);
System.out.println(time);
list.add(job);
}
}

// displaying average turnaround time
System.out.print("\nAverage turnaround time (RR): ");
System.out.printf("%.2f / %d = %.2f", turnaround, jobs.keySet().size(), (turnaround/ jobs.keySet().size()));
System.out.println("\n**********************************************************************");
}

}

________________________________________________________________________________________________________________________________

5jobs.txt

Job1
10
Job2
5
Job3
8
Job4
18
Job5
12

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

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.Scanner;

class ShortestJobFirst {
    public static void shortestJobFirst(LinkedHashMap<String, Integer> jobMap, int time, float turnaround) {

        System.out.println("Shortest-Job-First (SJF): \n");
        System.out.println("Job\t\tStart Time\tEnd Time\tJob Description\n");

        // displaying start times, calculating end time
        for (String job : jobMap.keySet()) {
            System.out.print(job + "\t\t" + time + "\t\t");
            time += jobMap.get(job);
            turnaround += time;
            System.out.println(time + "\t\t" + job + " completed at time " + time);
        }

        // displaying average turnaround time
        System.out.print("\nAverage turnaround time (SJF): ");
        System.out.printf("%.2f / %d = %.2f", turnaround, jobMap.keySet().size(), (turnaround / jobMap.keySet().size()));
        System.out.println("\n**********************************************************************");
    }

}

class RoundRobin {
    public static void roundRobin(ArrayList<String> list, LinkedHashMap<String, Integer> jobs, int time, float turnaround, int time_slice) {

        Map<String, Integer> jobMap = jobs.entrySet()
                .stream().collect(Collectors.toMap(Map.Entry<String, Integer>::getKey, Map.Entry<String, Integer>::getValue));

        for (String job : jobs.keySet())
            list.add(job);
        
        System.out.println("Round Robin with time slice = " + time_slice);
        System.out.println("Job\t\tStart Time\tEnd Time\tJob Description");

        while (!list.isEmpty()) {

            String job = (String) list.remove(0);
            System.out.print(job + "\t\t" + time + "\t\t");

            if ((Integer) jobMap.get(job) <= time_slice) {
                time += (Integer) jobMap.get(job);
                turnaround += time;
                jobMap.put(job, 0);
                System.out.println(time + "\t\t" + job + " completed at time " + time);
            } else {
                time += time_slice;
                jobMap.put(job, (Integer) jobMap.get(job) - time_slice);
                System.out.println(time);
                list.add(job);
            }
        }

// displaying average turnaround time
        System.out.print("\nAverage turnaround time (RR): ");
        System.out.printf("%.2f / %d = %.2f", turnaround, jobs.keySet().size(), (turnaround / jobs.keySet().size()));
        System.out.println("\n**********************************************************************");
    }

}

public class Main {
    public static void main(String[] args) throws IOException {

        Scanner scan = new Scanner(new File(args[0]));

        // linkedhashmap used to maintain order jobs are read
        LinkedHashMap<String, Integer> jobs = new LinkedHashMap<>();

        // reads each value, first the string (job title), then its value (time)
        while (scan.hasNextLine()) {
            jobs.put(scan.nextLine(), Integer.parseInt(scan.nextLine()));
        }

        // checks for an empty file
        if (jobs.isEmpty()) {
            System.out.println("ERROR: File is empty. Please try again.");
            System.exit(0);
        }
        ArrayList<String> list = new ArrayList<>();

        // specific method that sorts linkedhashmap by values in ascending order
        LinkedHashMap<String, Integer> jobMap = jobs.entrySet().stream().sorted(Map.Entry.comparingByValue()).collect(Collectors
                .toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));
        
        ShortestJobFirst.shortestJobFirst(jobMap, 0, 0);
        
        RoundRobin.roundRobin(list, jobs, 0, 0, 2);
        
        list.clear();
        RoundRobin.roundRobin(list, jobs, 0, 0, 5);

        scan.close();
    }

}

**************************************************

Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.

Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.

Add a comment
Know the answer?
Add Answer to:
Java: Hello, can someone please find a way to call my arraylist "list" and linkedhashmap called...
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
  • Implement a greedy strategy in JAVA which takes in a list of job object ( each...

    Implement a greedy strategy in JAVA which takes in a list of job object ( each job object consist of Job id (integer) , startTime (float) and endTime(float)) and outputs a list of non-conflicting jobs according to their start time. (Implement the given method provided in the code). Example of Input: id startTime endTime 1 4 7 2 3 5 3 7 9 CODE import java.util.Scanner; import java.util.List; import java.util.ArrayList; import java.io.InputStream; public class JobScheduling { public static final Strategy...

  • You will write a single java program called MadLibs. java.

    You will write a single java program called MadLibs. java. This file will hold and allow access to the values needed to handle the details for a "MadLibs" game. This class will not contain a maino method. It will not ask the user for any input, nor will it display (via System.out.print/In()) information to the user. The job of this class is to manage information, not to interact with the user.I am providing a MadLibsDriver.java e^{*} program that you can...

  • Hi All, Can someone please help me correct the selection sort method in my program. the...

    Hi All, Can someone please help me correct the selection sort method in my program. the output for the first and last sorted integers are wrong compared with the bubble and merge sort. and for the radix i have no idea. See program below import java.io.*; import java.util.ArrayList; import java.util.Scanner; public class Sort { static ArrayList<Integer> Data1 = new ArrayList<Integer>(); static ArrayList<Integer> Data2 = new ArrayList<Integer>(); static ArrayList<Integer> Data3 = new ArrayList<Integer>(); static ArrayList<Integer> Data4 = new ArrayList<Integer>(); static int...

  • How can I solved my Java Program for DelivC

    //Graph Class: import java.util.ArrayList; //Graph is a class whose objects represent graphs.  public class Graph {     ArrayList<Node> nodeList;     ArrayList<Edge> edgeList;         public Graph() {         nodeList = new ArrayList<Node>();         edgeList = new ArrayList<Edge>();         }         public ArrayList<Node> getNodeList() {         return nodeList;    }    public ArrayList<Edge> getEdgeList() {         return edgeList;    }    public void addNode(Node n) {         nodeList.add(n);    }    public void addEdge(Edge e) {         edgeList.add(e);    }    public String toString() {         String s = "Graph g.\n";         if (nodeList.size() > 0) {             for (Node n : nodeList) {         // Print node info         String t = "\nNode " + n.getName() + ", abbrev " + n.getAbbrev() + ", value " + n.getVal() + "\n";         s = s.concat(t);         }         s = s.concat("\n");             }         return s;     }  } // Node Class: import java.util.ArrayList;  // Node is a class whose objects represent nodes (a.k.a., vertices) in the graph.  public class Node {    String name;     String val; // The value of the Node     String abbrev; // The abbreviation for the Node     ArrayList<Edge> outgoingEdges;     ArrayList<Edge> incomingEdges;             String color; //Create the color of the TYPE Node List     int start; //Create the Starting Time     int end; //Create the Ending Time             public Node( String theAbbrev ) {         setAbbrev( theAbbrev );         val = null;         name = null;         outgoingEdges = new ArrayList<Edge>();         incomingEdges = new ArrayList<Edge>();     }         public String getAbbrev() {         return abbrev;     }         public String getName() {         return name;     }         public String getVal() {         return val;     }         public ArrayList<Edge> getOutgoingEdges() {         return outgoingEdges;     }         public ArrayList<Edge> getIncomingEdges() {         return incomingEdges;...

  • Can someone help me with my code.. I cant get an output. It says I do...

    Can someone help me with my code.. I cant get an output. It says I do not have a main method. HELP PLEASE. The instruction are in bold on the bottom of the code. package SteppingStones; //Denisse.Carbo import java.util.Scanner; import java.util.ArrayList; import java.util.List; public class SteppingStone5_Recipe { private String recipeName; private int servings; private List<String> recipeIngredients; private double totalRecipeCalories; public String getRecipeName() { return recipeName; } public void setRecipeName (string recipeName){ this.recipeName = recipeName; } public int getServings() { return...

  • Can anyone identify which OO Design Patterns are being used in the following code?: package mis;...

    Can anyone identify which OO Design Patterns are being used in the following code?: package mis; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Scanner; class helpDeskGuidline{    private void setGuideLine(){           }    public void rateService(){           } } public class HelpDeskService extends helpDeskGuidline{ //HelpDeskService class extends helpDeskGuidline this    //called inheritance    private static int ticketId=1;    Ticket ticket; // HelpDeskService class using ticket class object. this is has-A relationship (aggregation)          ArrayList<Ticket> allTicket=new ArrayList<>();    HashMap<Ticket,Person> ticketAllocation=new HashMap<>();    HashMap<Person,Integer> assignee=new HashMap<>();    HelpDeskService(){        Person...

  • How to build Java test class? I am supposed to create both a recipe class, and...

    How to build Java test class? I am supposed to create both a recipe class, and then a class tester to test the recipe class. Below is what I have for the recipe class, but I have no idea what/or how I am supposed to go about creating the test class. Am I supposed to somehow call the recipe class within the test class? if so, how? Thanks in advance! This is my recipe class: package steppingstone5_recipe; /** * *...

  • 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...

  • please edit my java code perferably on jgrasp version 50.0 , wont complie correctly :( the...

    please edit my java code perferably on jgrasp version 50.0 , wont complie correctly :( the program is supposed to read from my input file and do the following        1) print out the original data in the file without doing anything to it.        2) an ordered list of all students names (last names) alphabetically and the average GPA of all student togther . 3) freshman list in alphabeticalorder by last name with the average GPA of the freshmen...

  • 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 =...

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