gpt4 book ai didi

java - 仅接受用户对 ArrayList 的唯一输入

转载 作者:行者123 更新时间:2023-12-01 22:33:07 26 4
gpt4 key购买 nike

我不知道如何只允许用户输入三个唯一的数字。我尝试创建另一个数组来添加输入并检查损坏数组以确保所有数字都是唯一的,但它似乎不起作用。感谢您的任何帮助!!

    ArrayList<Integer> damage = new ArrayList<Integer>();

ArrayList<Integer> unique = new ArrayList<Integer>();
for (int k = 0; k<=10; k++)
{
unique.add(k);
}
do
{
System.out.print("Attack or Defend? (A or D) ");
option = keyboard.nextLine().toUpperCase();
System.out.println();
switch (option)
{
case "A":
System.out.println("Enter three unique random numbers (1-10)");
for(int i = 0; i<3; i++)
{
System.out.print("number " + (i+1) + ": ");
input = keyboard.nextInt();
if (input < 1 || input > 10)
{
System.out.println("Error! Enter a valid number (1-10)");
}
else
{
if (unique.contains(input))
{
unique.remove(input);
System.out.println(unique);
damage.add(input);
System.out.println(damage);

i--;
}
else
{
unique.add(0, input);
System.out.println("Number is not unique!");
}

}
}
System.out.println(damage);
System.out.println();
UserDamage ahit = new UserDamage(damage, option);
name.getName();
ahit.setUserDamage(damage, option);
System.out.println("\n");
cpuHealth-=ahit.getUserDamage();
cpu.setCpuDamage();
userHealth-=cpu.getCpuDamage();
System.out.println("\n\nHealth left: " + userHealth);
System.out.println("Computer health left: " + cpuHealth + "\n");
damage.clear();
option = null;
break;


default:
System.out.println("Invalid selection.");
break;
}
}
while(userHealth>0 || cpuHealth >0);

最佳答案

使用 java.util.List 中的 contains 方法来确定该项目是否已存在。来自 Javadoc:

boolean contains(Object o)

Returns true if this list contains thespecified element. More formally, returns true if and only if thislist contains at least one element e such that (o==null ? e==null :o.equals(e)).

关于java - 仅接受用户对 ArrayList 的唯一输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27325239/

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