gpt4 book ai didi

java - 连续输入错误时,循环中断java

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:01:55 25 4
gpt4 key购买 nike

当您连续两次输入随机值(如“i”)时,程序将终止。我希望这样“无效数据请重试”然后是“你想再玩一次吗”一直重复直到输入 N 或 Y。

7 8 5
No numbers match
Do you want to play again?
i
Invalid data please try again
Do you want to play again?
i
Thank you for using this program

应该是:

7 8 5
No numbers match
Do you want to play again?
i
Invalid data please try again
Do you want to play again?
i
Invalid data please try again
Do you want to play again?

...等等。

代码:

import java.util.Random;
import java.util.Scanner;

public class TestSlotMachine {

public static void main(String[] args) {
String choice;

Scanner keyboardScanner = new Scanner(System.in);

do {
Random randomNumber = new Random();
int slot1, slot2, slot3;

slot1 = randomNumber.nextInt(9);
slot2 = randomNumber.nextInt(9);
slot3 = randomNumber.nextInt(9);

System.out.println(slot1+" "+slot2+" "+ slot3);

if (slot1 != slot2 && slot1 != slot3 && slot2 != slot3) {
System.out.println("No numbers match");
}
else if (slot1 == slot2 && slot2 == slot3) {
System.out.println("Three numbers match");
}
else {
System.out.println("Two numbers match");
}

System.out.println("Do you want to play again?");
choice = keyboardScanner.next();
if (!choice.equalsIgnoreCase("n") && !choice.equalsIgnoreCase("y")) {
System.out.println("Invalid data please try again");
System.out.println("Do you want to play again?");
choice = keyboardScanner.next();
}

} while (choice.equalsIgnoreCase("y"));

System.out.println("Thank you for using this program");
keyboardScanner.close();
}
}

最佳答案

if (!choice.equalsIgnoreCase("n") && !choice.equalsIgnoreCase("y"))

可以变成

while (!choice.equalsIgnoreCase("n") && !choice.equalsIgnoreCase("y"))

关于java - 连续输入错误时,循环中断java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27899932/

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