我正在尝试从System.in
读取。
输入的类型如下:
第一个数字是测试用例的数量,然后是整数,然后是一些行。
2
10
c 1 5
c 2 7
q 7 1
1
q 1 1
c 1 1
q 1 1
问题是,当我完成最后一个测试时,尽管循环中有 sc.hasNext()
条件,但 while 循环不会退出。
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int testCases = sc.nextInt();
for(int i=0;i<testCases; i++){
int numberOfQuestions = 0;
int numberOfSuccessufulQuestions = 0;
int computerNumber = sc.nextInt();
Graph g = new Graph();
while(!sc.hasNextInt() && sc.hasNext()){
String type = sc.next();
if (type.trim().equals("\n"))
break;
if(type.equals("c")){
int a = sc.nextInt();
int b = sc.nextInt();
g.setEdge(a, b);
}else if(type.equals("q")){
visited = new HashMap<>();
int a = sc.nextInt();
int b = sc.nextInt();
numberOfQuestions++;
if(a == b){
numberOfSuccessufulQuestions++;
}
else if(g.isNodeExist(a) && g.isNodeExist(b)){
if(connected(g, a, b)){
numberOfSuccessufulQuestions++;
}
}
}
}
System.out.println(numberOfSuccessufulQuestions+ ","+ (numberOfQuestions - numberOfSuccessufulQuestions) );
}
}
最佳答案
扫描仪没问题,因为它看起来像您想要输入临时信息。
问题是 sc.next() 不会通过在控制台中简单地按 Enter 键来触发。
我在这里看到的解决方案是使用命令终止循环。
不要使用 if (type.trim().equals("\n"))
,而是使用 (type.trim().equals("exit"))
关于java - 当没有更多行可读取时扫描仪停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36121533/