gpt4 book ai didi

java - 如何在不绕过另一代码块的情况下执行一段代码? java

转载 作者:行者123 更新时间:2023-12-01 17:16:07 27 4
gpt4 key购买 nike

标题可能没有提供太多信息。但事情就是这样。

我希望用户在第二次经过那里时执行代码。我所做的是制作一个 if 语句,但现在我注意到,有了这个,其余的就没有被执行。

Scanner input = new Scanner(System.in);
Random dice = new Random();
int counter = 1;
boolean playing = true;
boolean firstTimmer = true;
boolean got = true;

System.out.println("Welcome to numberMind! From 0 to x, you'll try to guess the random number!");
System.out.println("To quit, guess \"-1\".");
System.out.print("Insert x: ");
int x = 1+input.nextInt();
int objective = dice.nextInt(x);
System.out.print("Ok, I'm ready! What's your first guess? ");
int guess = input.nextInt();


while (playing){
if (guess == -1){
playing = false;
break;
}else if (!firstTimmer){
got = true;
System.out.print("Do you want to change the number range? Yes(1) No(2)");
guess = input.nextInt();
if (guess == 1){
System.out.print("Insert the new x: ");
x = 1+input.nextInt();
}else if(guess == 2){
System.out.println("Let's go then!");
}else{
System.out.print("I didn't ask for that number did I? x won't change.");
}
}else{
while(got){
if (objective == guess){
firstTimmer = false;
System.out.println("You guessed it in "+counter+" times!");
counter = 1;
System.out.print("Do you want to paly again? Yes(1) No(2) ");
guess = input.nextInt();
if (guess == 1){
System.out.println("Great! Here we go...");
got = false;
break;
}else if (guess == 2){
System.out.print("Thanks for playing!");
got = false;
playing = false;
}else{
System.out.println("We didn't ask for that. NOW YOU PLAY SOME MORE!");
got = false;
break;
}
break;
}else if (guess == -1){
System.out.println("You quited :(");
break;
}else if (guess == -2){
System.out.println("The correct answer is "+ objective);
}else if (counter >= 5 && (counter -5) % 3 == 0 ){
if (objective % 2 == 0){
System.out.println("The number is pair.");
}else{
System.out.println("The number is odd.");
}
}
System.out.println("You have tryed " + counter++ + " times.");
System.out.print("What's your guess? ");
guess = input.nextInt();
}
}
}

我想要运行的代码位于最后一个 else 之后。我没有看到任何可以解决它的东西。谢谢

最佳答案

我们首先要问自己else何时会实现:当guess != -1firstTimmer == true时。您无需设置 firstTimmer,它需要设置为 true 才能通过 else block 。您还需要删除 else if 中的 break,否则它在下一次迭代中永远不会到达 else。

此外,在 if 语句中同时使用 playing = falsebreak 是多余的。两者都会分别做同样的事情。

while (playing){
if (guess == -1){
playing = false;
break;
}else if (!firstTimmer){
got = true;
System.out.print("Do you want to change the number range? Yes(1) No(2)");
guess = input.nextInt();
if (guess == 1){
System.out.print("Insert the new x: ");
x = 1+input.nextInt();
}else if(guess == 2){
System.out.println("Let's go then!");
}else{
System.out.print("I didn't ask for that number, x won't change.");
}
firstTimmer = true;
//break;
}else{

关于java - 如何在不绕过另一代码块的情况下执行一段代码? java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22054590/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com