如何在循环外获取布尔值

时间:2018-09-21 04:22:10

标签: java jframe

我不确定如何在循环外获取布尔值。我检查了不同的网站,他们曾建议我尝试破坏“ if”语句中的循环,如果该语句应返回正确的值。不幸的是,那些没有用。 谢谢。

主要有问题的代码:

/**
 * Figures out if a game is currently running..
 * @return
 * @throws IOException 
 */
private boolean isGame() throws IOException {
    boolean gameRunning = false;
    Process p = Runtime.getRuntime().exec("tasklist");
    // Reads all the current processes running.
    BufferedReader readTasks = new BufferedReader(new InputStreamReader(p.getInputStream()));

    // CURRENT PROBLEM; IT DOESN'T RETURN CORRECT VALUE AND IDK HOW TO FIX IT.

    // Read through all tasks and see which one is running the game.
    boolean tasksAvaliable = readTasks.ready();
    while (tasksAvaliable) {
        String task = readTasks.readLine();
        if (task.startsWith("svchost.exe")) {
            gameRunning = true;
            return gameRunning;
            //System.out.println("You're good to go.");
            //tasksAvaliable = false;
        } else {
            tasksAvaliable = readTasks.ready();
        }
    }
    return gameRunning;
}

2 个答案:

答案 0 :(得分:0)

我认为问题出在调用ready()上。 JavaDoc:告知此流是否已准备好被读取。

问题在于,ready可能返回false,尽管将来可能还会读取更多数据。 您应该编写一个无限循环,如果readLine返回null:

for (;;) {
    String task = readTasks.readLine();
    if (task == null) {
        break;
    }
    ...
}

答案 1 :(得分:0)

您必须等待命令任务列表响应。

/**
         * Figures out if a game is currently running..
         * @return
         * @throws IOException 
         */
        private boolean isGame() throws IOException {
            boolean gameRunning = false;
            Process p = Runtime.getRuntime().exec("tasklist");

            // Reads all the current processes running.
            BufferedReader readTasks = new BufferedReader(new InputStreamReader(p.getInputStream()));

            // CURRENT PROBLEM; IT DOESN'T RETURN CORRECT VALUE AND IDK HOW TO FIX IT.

            // Read through all tasks and see which one is running the game.
            String task;
            while ((task = readTasks.readLine()) != null) {
                if (task.startsWith("svchost.exe")) {
                    gameRunning = true;
                    return gameRunning;
                    //System.out.println("You're good to go.");
                }
            }
            return gameRunning;
        }