首页 > 解决方案 > 需要帮助保持我的流程运行,直到我输入关键字

问题描述

编写一个创建和启动游戏的 main 方法。用户应该能够重复输入字母。每次进入后,应发布当前的比赛场地。当用户输入 x 时,程序将被终止。那是我的练习。

我试图用 do/while 循环来做,但我就是不能让它工作。然后我尝试使用 aRuntimeException并使用 try/catch 但我也失败了。如果有人能提示我正确的方向,我将不胜感激:)。

public class SpaceInvaders {

    private static final char[][] field = new char[5][8];
    static int x = (int) ((Math.random() * 8));

    public static void field(){
        Arrays.fill(field[0], 'o');
        for(int k=1; k<5; k++){
            Arrays.fill(field[k],' ');
        }
        field[4][x] = 'V';
        outputArray();
    }
    public static void outputArray(){
        for (char[] chars : field) {
            for (char aChar : chars) {
                System.out.print(aChar + " ");
            }
            System.out.println();
        }
    }
    public static void move(char input){
        if(input == 'a'){
            if(x == 0){
                x++;
            }
            field[4][x] = ' ';
            field[4][x - 1] = 'V';
            outputArray();
        }
        else if(input == 'd'){
            if(x == 7){
                x--;
            }
            field[4][x] = ' ';
            field[4][x + 1] = 'V';
            outputArray();
        }
        else if(input == 'x'){
            System.exit(0);
        }
    }
    public static void main(String[] args){
        field();
        Scanner s = new Scanner(System.in);
    }
}

标签: javajava.util.scanner

解决方案


您只需要在扫描仪周围循环等待键盘输入

public static void main(String[] args){
    field();
    Scanner s = new Scanner(System.in);
    while (true) {
        move(s.next().trim().charAt(0));
    }
}

推荐阅读