循环时无法停止 [英] Can't stop while loop
本文介绍了循环时无法停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我创建的这个游戏中,我遇到了一个问题。一切都很好,除了如果您由于某种原因失败而导致游戏重新启动,那不是我想要的。我想显示要设置的内容,然后中断循环,由于某些原因 break;
无法正常工作。
代码:
In this game that I created I ran into a problem. It all works great except that if you fail for some reason the game just restarts and that's not what I want. I want to display what I have it set to display and then break the loop, for some reason the break;
isn't working.
Code:
import java.util.Scanner;
import java.util.Random;
public class GuessingGame1_3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random rand = new Random();
System.out.print("Pick a number to guess between: ");
int userNumber = input.nextInt();
int random = rand.nextInt(userNumber);
if (random < 1) {
random = random + 1;
} else if (random > userNumber) {
random = random - 1;
}
while (true) {
System.out.print('\f');
System.out.print("Pick the amount of attempts you would like to have (Max of 10 attempts): ");
int userAttempts = input.nextInt();
if (userAttempts > 10) {
System.out.println("To Many Attempts");
System.out.println("");
} else if (userAttempts <= 10) {
System.out.println("Version: 1.3");
System.out.println("----------------------------------------------------------------------");
System.out.println("You have " + userAttempts + " attempts to guess the number or else you fail. Goodluck!");
System.out.println("");
System.out.println("Type 'begin' to Begin!");
String start = input.next();
System.out.print('\f');
if (start.equals("begin")) {
for(int i=1; i<userAttempts + 1; i++) {
System.out.print("Enter a number between 1-" + userNumber + ": ");
int number = input.nextInt();
if (number > random) {
System.out.println("Too Big");
System.out.println("");
} else if (number < random) {
System.out.println("Too Small");
System.out.println("");
} else if (number == random) {
System.out.println("Correct!");
break;
}
if (i == userAttempts) {
System.out.println("You have failed");
System.out.println("Number Was: " + random);
break;
}
}
} else if (!start.equals("begin")) {
System.out.print('\f');
System.out.println("Incorrect Command");
System.out.println("Please Exit Console And Retry");
break;
}
}
}
}
}
推荐答案
如果想中断
外循环,则可以使用嵌套循环,您可以添加标签前缀 1
With nested loops if you want to break
the outer loop you might add a label prefix1.
game: while (true) {
然后您可以
break game;
终止标有 game
的语句
1 另请参见 JLS-14.7。带标签的声明(部分说明)声明可能具有 标签 前缀。
1See also JLS-14.7. Labeled Statements which says (in part) Statements may have label prefixes.
这篇关于循环时无法停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文