我编写了一个简单的低级随机发生器,为我和我的 friend 玩的棋盘游戏创建一个角色。然而,写完之后,我意识到我还需要一种简单的方法来重新运行程序以生成新的随机字符。目前,我必须关闭程序然后重新运行它才能生成新角色。有什么简单的方法可以做到这一点吗?请注意,我是一名相当中级的编码员。
我在网上搜索过,发现的大多数解决方案都需要创建 GUI。这是我不愿意做的事情。我也尝试过使用 while
循环作为解决方案,但我还没有找到一种方法来暂停程序,直到按下按钮。
任何简单的事情都会受到赞赏。如果我必须做一些更复杂的事情,比如创建 GUI,我准备学习如何做。
最佳答案
您的问题有两种解决方案。使用 for 循环和使用 while 循环。
for 循环将运行代码块 x 次。例如
System.out.println("How many characters would you like? ");
Scanner scanner = new Scanner(System.in);
int result = scanner.nextInt();
for (int i = 0; i < result; i++) {
// Code to give user a character runs "result" amount of times
}
while 循环将无限期地运行,直到满足条件为止。例如
boolean anotherCharacter = true;
while (anotherCharacter) {
// Code to give user a character runs until "anotherCharacter" is false
System.out.println("Would you like another character? (yes/no) ");
Scanner scanner = new Scanner(System.in);
String result = scanner.next();
if (result.equalsIgnoreCase("no")) {
anotherCharacter = false;
}
}
根据您的情况,最佳选择取决于您在游戏开始时是否确切知道需要多少个角色。如果是这样,我会推荐 for 循环。但是,如果您不知道游戏开始时的字符数,我建议使用 while 循环。
关于java - 有没有什么简单的方法可以让方法/程序在按下特定按钮后重新运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58246182/