Reputation: 2274
Code:
int size=0;
Scanner in = new Scanner(System.in);
System.out.println("Enter size of the Graph");
size = in.nextInt();
System.out.println(size);
for (int i = 1; i <= size; i++) {
Scanner in2 =new Scanner(System.in);
while(in2.hasNextInt()){
int num = in2.nextInt();
System.out.print("(" + i + "," + num + ")"+",");
System.out.println();
}
System.out.println("out of the while loop");
}
Input & Output:
Enter size of the Graph
4
4
2 3 4
(1,2),
(1,3),
(1,4),
2 5 6
(1,2),
(1,5),
(1,6),
As you can see my program doesn't exists while loop. It still prints the value for i=1. What I am doing wrong?
Upvotes: 0
Views: 146
Reputation: 51030
int num = in2.nextInt();
try adding in2.nextLine();
after that.
Note:
You shouldn't be doing new Scanner(System.in);
multiple times.
Scanner in2 = new Scanner(System.in); // this is useless just use in
Upvotes: 1
Reputation: 178431
Your program is constantly waiting for a new feed, in order to terminate it - you should indicate the input was ended (or provide a non int
input).
To indicate the feed ended - you should provide EOF - which is ctrl+D
in linux and ctrl+Z
in windows.
Upvotes: 1