-1

this is my work class which adds works with their priority and ı used comparable interface to obtain priority among works.

public class Work implements Comparable<Work>{
    private String work;
    private int pri;
    
    //this is constuctor
    public Work(String work, int pri){
        this.work = work;
        this.pri = pri;
    } 

    //this is implementation of compareTo method
    @Override
    public int compareTo(Work o) {
        if (this.pri < o.pri)
            return -1;
        else
            return 1;
    }

    @Override
    public String toString() {
        return  this.work;
    }   
}

and this is the part which is in regard to the priority queue

        int option = 0;
        String work;
        int urgency;
        PriorityQueue<Work> works = new PriorityQueue<Work>();
        do {
            System.out.println("enter what you want\n1.add work\n2.next\n3.quit ");
            option = scan.nextInt();
            if (option == 1) {
                System.out.println("what is work ");
                work = scan.nextLine();
                scan.nextLine();
                System.out.println("how is your work urgency ");
                urgency = scan.nextInt();
                works.add(new Work(work, urgency));
            }
            if (option == 2) {
                while (!works.isEmpty()) {
                    System.out.println(works.poll());
                }
            }
        } while (option != 3);

while option 1 and 3 works well, option 2 is not working it understand the work just blank line and output is just a blank line. thanks in advance!!

sorry for giving not the necessary info because of StackOverflow rules(mostly code).

sc0der
  • 4,152
  • 2
  • 12
  • 24

1 Answers1

0

Your code snippet didn't show us how scan was declared, but from the method names I'm guessing that it's a java.util.Scanner. That can be difficult to use.

System.out.println("what is work ");
work = scan.nextLine();
System.err.println("HAVE READ >>" + work + "<< into work");   // <------
scan.nextLine();
System.out.println("how is your work urgency ");

A good starting point would be the line I've added there. As soon as you read that input, print it back out, because that's what your toString is returning. If your toString is not doing what you expect, it's a good sign that the input to "work" might not be what you're assuming it is.

You might want to move to some kind of loop there also, like

work = null;
while (work is null or empty or otherwise invalid) {
    System.out.print("what is work?  ");
    work = scan in the text;
    test work for empty input, like a line of only spaces, etc;
}
// do the same thing for urgency, etc

But that can come after checking that the nextLine() is doing what you think it is.

Don't forget to remove the System.err line once you're done!

Ti Strga
  • 1,254
  • 18
  • 35