2

While trying out quick-find in Java, I am having an issue. In the main function, the code after while loop is not getting executed even though it doesn't seem like an infinite loop case. Adding the full code and sample input and output.

Update :- The issue in the blocking nature of hasNext(), hasNext() keeps on waiting for an input. Used Ctrl+Z after giving all input to terminate the stream which helped with process the remaining code after while loop

Below is the full code (with issue) -

public class UF {

private int[] id;   

public UF(int n){
    this.id = new int[n];
    for(int i = 0; i < n; i++){
        this.id[i]=i;
    }
}

public boolean connected(int p, int q){
    return(id[p] == id[q]);
}

public void union(int p, int q){
    System.out.println("enter union");
    int pid = id[p];
    int qid = id[q];

    for(int i = 0; i < id.length; i++){
        if(id[i] == pid){
            id[i] = qid;
        }
    }
    System.out.println("Leave union");      
}

public void display(){
    System.out.println("This is what we got");
    for(int i = 0; i < id.length; i++){
        System.out.println(i + " => " + id[i]);
    }
}

// Main method
public static void main(String[] args) {
    Scanner in  = new Scanner(System.in);

    int n = in.nextInt();
    UF uf1 = new UF(n);
    int count = 0;

    while(in.hasNext())
    {
        //System.out.println("here again");
        int p = in.nextInt();
        int q = in.nextInt();
        uf1.union(p, q);
        count++;
        System.out.println(count);
    }
    in.close();

    /*********************************/
    /* BELOW MESSAGE IS NOT PRINTING */ 
    /*********************************/
    System.out.println("out of while");     
}
}

Sample Input ->

10
4 5
6 7
8 9
9 7

Corresponding output ->

enter union
Leave union
1
enter union
Leave union
2
enter union
Leave union
3
enter union
Leave union
4
Parzival
  • 585
  • 2
  • 12
  • Under what circumstances would you expect the code to stop? You are just requesting more ints after ints, you are not leaving the `while` loop. – luk2302 Jan 23 '17 at 20:19
  • When your input is complete, the while loop is just waiting for the next line infinitely. You need some condition to exit the loop, like a character to mark the end of the input or something. – Alex Jan 23 '17 at 20:25

0 Answers0