[英]Why my program in not exiting out of while loop?
码:
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");
}
输入输出:
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),
正如您所看到的,我的程序在循环时不存在。 它仍然打印i = 1的值。 我做错了什么?
int num = in2.nextInt();
尝试添加in2.nextLine();
之后。
注意:
你不应该做new Scanner(System.in);
多次。
Scanner in2 = new Scanner(System.in); // this is useless just use in
您的程序一直在等待新的订阅源,以便终止它 - 您应该指示输入已结束(或提供非int
输入)。
要指示Feed已结束 - 您应该提供EOF - 在linux中为ctrl+D
,在Windows中为ctrl+Z
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.