java - 需要帮助保持我的流程运行,直到我输入关键字
问题描述
编写一个创建和启动游戏的 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);
}
}
解决方案
您只需要在扫描仪周围循环等待键盘输入
public static void main(String[] args){
field();
Scanner s = new Scanner(System.in);
while (true) {
move(s.next().trim().charAt(0));
}
}
推荐阅读
- java - 如何修复 "{"name":"error","attributes":{"message":"Exception occurred in the Test Runner." 在 VS 代码中
- google-bigquery - BigQuery 将 rank / percent_rank 应用于带有 WHERE 子句的列
- javascript - React+Firebase:如何将项目添加到 Firebase 实时数据库中
- node.js - 如何使用来自 Node.JS 客户端的容器映像启动 Google Cloud 实例?
- python - 如何在列上循环 .replace 以将多个字符串更改为一个字符串?
- java - 如何在 IntelliJ IDEA 中生成 JPA Hibernate Metamodel 类?
- python - Linregress 输出似乎不正确
- sql-server - 将两个查询的结果相除,在第三个查询中得到结果
- python - 如何检测 pygame 中 Sprite 类的 2 个表面对象之间的碰撞?
- python - 每个客户提供不同样本大小的样本