gpt4 book ai didi

java - 不要重复字符 - Java

转载 作者:行者123 更新时间:2023-12-02 01:54:08 26 4
gpt4 key购买 nike

如果输入的字符已被使用,我试图让程序打印出错误。如果您检查 else If 语句,从技术上讲它会运行,但我不希望它每次都打印。仅当该角色已在另一轮中被选择时。

while (!userCorrect) {
Scanner input = new Scanner(System.in);
System.out.print("Guessing (round " + roundNumber + "): Choosing your letter from a-z: ");
String letters = input.nextLine();
createString(letters.length());
if (letters.length () > 1) { //code will print an error if the user selects more than 1 character
System.out.println("You should not enter more than 1 character");
}
else if (letters.length()==letters.length()) { //print error if the character has been chosen already
System.out.println(letters + " has been chosen before, try again");
}
else {
System.out.println("end (round " + roundNumber + ")");
roundNumber++;
}
}

我得到的最接近的是letters.length() == letters.length();但我知道这样做总是会打印错误。您认为我可以在其中放入一个参数,使其跳过第一轮并仅在第二轮开始时才开始查找吗?

最佳答案

我知道你已经有了答案,但我想指出一些事情

  • 不要每次都在循环中创建新的 Scanner 对象
  • 使用继续避免嵌套if-else
  • 有多种方法可以存储字符,例如使用 List 或 Set 集合或 StringBuffer 或简单的 String。
  • 您的 boolean 变量的名称是...
  • 我忽略了 createString 方法并跳过了 userCorrect,因为他们不清楚如何使用

(我也结束了自己的循环退出条件,因为只是为了有一个)

Scanner input = new Scanner(System.in);
int roundNumber = 1;
boolean isUserCorrect = false;

String selected = "";

while (true) {
System.out.print("Guessing (round " + roundNumber + "): Choosing your letter from a-z: ");
String letters = input.nextLine();

if (letters.length () > 1) { //code will print an error if the user selects more than 1 character
System.out.println("You should not enter more than 1 character");
continue;
}

if (selected.contains(letters)) {
System.out.println(letters + " has been chosen before, try again");
continue;
}

selected = selected.concat(letters);
System.out.println("end (round " + roundNumber + ")");
roundNumber++;
if (roundNumber > 5) {
System.out.println("Selected characters: " + selected);
break;
}
}
input.close();

关于java - 不要重复字符 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52557707/

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