首页 > 解决方案 > java - 如何通过让用户在java中按下键盘上的特定键来终止无限控制台循环?

问题描述

大家好,你们可以看到这是一个无限循环,我问我是否可以在键盘上分配一个键,只要用户按下这个键,它就会终止并停止这个循环。请注意,我正在尝试在控制台中执行此操作,而不是 UI

     do{
//some calculations here
}while(true);

    ```

标签: java

解决方案


做你想做的两个例子:

第一个例子:

    Scanner sc = new Scanner(System.in);
    String input = null;
    
    do {
        System.out.println("Type X to exit and hit enter");
        input = sc.next();
    } while(!input.equalsIgnoreCase("x"));
    
    sc.close();

第二个例子:

    Scanner sc = new Scanner(System.in);
    String input = null;
    do {

        System.out.println("Type X to exit and hit enter");
        input = sc.next();
        
        if (input.equalsIgnoreCase("x")) {
            break;
        }
    } while(true);

    sc.close();

推荐阅读