0

I have the following method which takes user input and applies an algorithm to it. However when I try to print the String process_name, stored in the fcfs ArrayList it comes out empty. But the burst_time and arrival_time fields in the same fcfs ArrayList get output to the console exactly as the user inputted the data. Not really sure what could be wrong.

public static void algorithm() {


        ArrayList<Process> fcfs = new ArrayList<>();

        Scanner scan = new Scanner(System.in);

        System.out.println("Process name,CPU Burst Time,Arrival time\n ");

        while (!scan.next().equalsIgnoreCase("finish")) {

            Process p = new Process();

            String pn = "";
            String bt = "";
            String at = "";
            pn = input.nextLine();
            bt = input.nextLine();
            at = input.nextLine();

            System.out.println("Process name, CPU Burst Time, Arrival time\n ");

            p.process_name = pn;
            p.burstTime = Float.parseFloat(bt);
            p.arrivalTime = Float.parseFloat(at);
            fcfs.add(p);

        }

        

        {

            Collections.sort(fcfs, new comp());
        }

    

        
        result(fcfs, fcfs.size(),false)

    }

This is the Process class:

class Process {
    String process_name;
    float burstTime;
    float arrivalTime;
    float compTime = 0;
    boolean status = false;

}

General Grievance
  • 4,555
  • 31
  • 31
  • 45

2 Answers2

2

scan.next() function gets the next input string. That is why you get an empty line for process name because the name is already taken by the next function in the while condition. Either use hasNext() to check if there is a next line or get and put input to a string variable and compare it with the word 'finish'.

You can see the explanation in the documentation: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#next()

Quoting from the documentation: "next : Finds and returns the next complete token from this scanner"

Aysu Sayın
  • 191
  • 7
1

The problem is because of using next() instead of nextLine(). Check Scanner is skipping nextLine() after using next() or nextFoo()? to learn more about it.

Replace

while (!scan.next().equalsIgnoreCase("finish"))

with

while (!scan.nextLine().equalsIgnoreCase("finish"))

Also, it's better to use do...while which guarantees to execute its body at least once i.e.

do {

    Process p = new Process();

    String pn = "";
    String bt = "";
    String at = "";
    pn = input.nextLine();
    bt = input.nextLine();
    at = input.nextLine();

    System.out.println("Process name, CPU Burst Time, Arrival time\n ");

    p.process_name = pn;
    p.burstTime = Float.parseFloat(bt);
    p.arrivalTime = Float.parseFloat(at);
    fcfs.add(p);

} while (!scan.nextLine().equalsIgnoreCase("finish"));
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110