Reputation: 1
I am at a loss of how I would only allow a user to enter three unique numbers. I have tried to create another array that adds the input and checks with the damage array to make sure all numbers are unique, but it does not seem to work. Thank you for any help!!
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);
Upvotes: 0
Views: 1061
Reputation: 156
You are close. Just need some more logic work in here and using what Mike Kobit suggested.
ArrayList<Integer> damage = new ArrayList<Integer>();
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(damage.contains(input) == false && input > 0 && input <= 10)
damage.add(input);
else{
System.out.println("Error! Enter an unique valid number (1-10)");
i--;
}
}
The i-- is for the loop so if you entered in bad value 3 times, no values would go into the array.
Upvotes: 1
Reputation: 200
The contains() method should be useful for you. So entering one number can look like this:
while(input > 10 || input < 0 || damage.contains(input)) {
System.out.print("number " + (i+1) + ": ");
input = keyboard.nextInt();
}
Upvotes: 0
Reputation: 47249
Use the contains
method from java.util.List
to determine if the item is already present. From the Javadoc:
boolean contains(Object o)
Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).
Upvotes: 2