java - 当没有更多行可读取时扫描仪停止

标签 java

我正在尝试从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/

相关文章:

java - 如果存在强引用,保证返回现有对象的线程安全对象池?

java - 如何获取 ICompilationUnit 的保存版本?

java - 在java中删除数据文件的部分内容

java - 如何订购此链接列表?

java - Maven 依赖项缺少 Artifact

java - Camel : doTry in the Choice clause

java - 如何从包含另一个数组的所有元素的数组中获取所有可能的组合

java - 在来自 Android Volley 的 POST 请求中发送 JSON 对象接收 java Restful Webservices

java - 检查一个点是否在指定的矩形内

java - Spring Constant 将忽略并非所有大写字段