Accept only unique input from a user into an ArrayList - java

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);

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)).

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.

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();
}

Related

Replacing an Element

I'm working on code that shows the simple operation of an array. I can't seem to make it work at the part of re-inserting a deleted element inside my created array. My goal is to put another element inside another deleted element (when I delete an element it becomes 0). My insert case just tells the duplicate input, it does not let me resume in the deleted element at a certain position.
case 2:
{
if (limit1 < 5 || limit1 > 20){
System.out.println("Error: Invalid Array Limit");
System.out.println("Press Any Key To Continue...");
new java.util.Scanner(System.in).nextLine();
System.out.print('\u000C');
m();
}
else{
System.out.println("Enter the " + array.length + " numbers now.
Or enter -1 to exit");
int i = 0;
while(i < array.length){
array[i] = in.nextInt();
boolean dups = false;
if(array[i] != -1){
for(int k = 0; k < i; k++)
if(array[k] == array[i])
{
System.out.println("Error: Duplicate Element");
System.out.println("Please Enter Another Value");
dups = true;
break;
}
if(!dups){
i++;}
}
else{
array[i] = 0;
System.out.println("Exit Confirmed");
System.out.println("Press Any Key To Continue...");
new java.util.Scanner(System.in).nextLine();
System.out.print('\u000C');
m();
}
}
System.out.println("You have entered the "+ limit1 + " numbers");
System.out.println("Press Any Key To Continue...");
new java.util.Scanner(System.in).nextLine();
System.out.print('\u000C');
m();
}
}
Another problem is, if I input a sentinel value (-1), it just makes the current input position 0. I just wish to exit the case not put a 0 at the position
I see some problems with your code. Using switch statements without any break statements is not a good practice. You can easily refactor your method to use a while loop like this:
public void e() {
do {
m();
choice1 = in.nextInt();
cls();
if (choice1 > 0) {
processChoice(); // contains switch block for processing input
}
} while (choice1 > 0); // Loop will terminate when user presses 0
}
This should also exit your program whenever user presses 0.
I see a problem in your Insertion into array block. You seem to be assigning value received from input directly to array[i]. What's the point of checking if it's a duplicate value after assigning it to array[i]. I think you should do something like this:
while (i < array.length) {
int currentInput = in.nextInt();
boolean dups = false;
if (array[i] != -1) {
for (int k = 0; k < i; k++)
if (array[k] == currentInput) {
System.out.println("Error: Duplicate Element");
System.out.println("Please Enter Another Value");
dups = true;
break;
}
if (!dups) { // currentInput not a duplicate; assign to array[i]
array[i] = currentInput;
i++;
}
Regarding exiting on providing -1, You should probably remove this line array[i] = 0 in order to not assign 0 to array[i]:
if (array[i] != -1) {
// ...
} else {
System.out.println("Exit Confirmed");
System.out.println("Press Any Key To Continue...");
new Scanner(System.in).nextLine();
System.out.print('\u000C');
break;
}
Here are some errors I found in your code:
You go to newline in System.out.plintln("Enter the " + array.length + "...."); in the middle of the string, you should do something like that:
System.out.println("Enter the " + array.length + " numbers now." + "\nOr enter -1 to exit")
if the input is -1 you don't exit straight away but you do array[i]=0 (remember that array[i] now is array[-1])
then you don't break the loop after -1 is inputted
case shouldn't be enclosed in brackets and should always finish with break:
case 1:
//DO THINGS
//....
//...
break;
case 2:
//DO OTHER THINGS
//....
//...
break;
Here are some suggestions on how to improve it:
I don't remember very well Java, but I don't think you have to create a new Scanner every time
if I was you I would check if the input is -1 as the first thing (there are several ways to do that)
not using the brackets for the for is a bit confusing
you already break when a duplicate is found, so you don't need to check it again with if(!dups)
I hope this solves your problem.

Repeated letters logic not working in java

I am working on a version of hangman, and I need to include a condition that checks if a letter guess was already used. My repeated letters if statement is not working correctly. Any advice?
NOT FULL CODE. ONLY A PIECE IS SHOWN
char[] repeatedLetters = new char[26];
int incorrect = 0;
while (incorrect < 7)
{
System.out.println("\nGuess a letter: ");
char guess = kb.next().toUpperCase().charAt(0); // case insensitive
for (int i = 0; i < repeatedLetters.length; i++)
{
if (repeatedLetters[i] == guess) {
System.out.println("You already guessed " + guess + ".");
System.out.println("Guess a letter: ");
guess = kb.next().toUpperCase().charAt(0);
}
else
repeatedLetters[i] = guess;
}
Personally, I would suggest using a List instead of array.
List<Character> repeatedLetters = new ArrayList<>();
int incorrect = 0;
while (incorrect < 7)
{
System.out.println("\nGuess a letter: ");
char guess = kb.next().toUpperCase().charAt(0); // case insensitive
if (validateCharacter(guess) && repeatedLetters.contains(guess)) {
System.out.println("You already guessed " + guess + ".");
continue;
}
else {
repeatedLetters.add(guess);
}
// Other things
}
If you are not allowed to use a list, then you need to move the else block outside of the for loop, use a labelled while loop, and also manually count the number of repeated characters.
int repeatedCount = 0;
getInput : while (incorrect < 7) {
// ......
for (int i = 0; i < repeatedCount; i++) {
if (repeatedLetters[i] == guess) {
System.out.println("You already guessed " + guess + ".");
continue getInput;
}
}
repeatedLetters[repeatedCount] = guess;
repeatedCount++;

Java do while loop won't loop- Java (All int)

Code for menu options won't loop, but has no errors. I intentionally wrote it similar to my while loop that loops just fine. I have to use only integers, and my instructor did tell me to turn my inputs into variables. Most of it isn't quite finished but I'm working on that at the same time as trying to figure all this out.
//Loop to check user input
num=-1;
while (num<0)
{
//Getting user entered interger
System.out.print("Please enter a positive number: ");
num = kb.nextInt();
//Ensuring positive interger
if (num >= 0)
{
System.out.println("You've entered the number " + num + ".");
}
else
{
System.out.println("Error! The number you've entered is not a valid interger.");
}
}
copy = num;
//Printing menu loop
copy2 = -1;
do
{
//Menu making
System.out.println(" ");
System.out.println("1. Enter a new number.");
System.out.println("2. Print the number of odd digits, even digits, and zeros in the interger.");
System.out.println("3. print if the number is light or heavy.");
System.out.println("4. Print the prime numbers between 2 and the interger (inclusive).");
System.out.println("5. Quit the program.");
System.out.println(" ");
System.out.print("Please enter your menu choice: ");
choice = kb.nextInt();
copy2 =choice;
//Checking entry
if (0<copy2 && copy2<=5)
{
System.out.println("You chose option " +copy2+".");
}
//Option one
if (copy2 == 1)
{
System.out.print("Will work on soon.");
}
//Option two
if (copy2 == 2)
{
oddNum=0;
evenNum=0;
zero=0;
while (copy>0)
{
if (copy %10==0)
{
zero++;
}
else if (copy %2==1)
{
evenNum++;
}
else
{
oddNum++;
}
}
copy = copy/10;
System.out.println("Even numbers: " + evenNum+
"\nOdd numbers: "+ oddNum +
"\nZeros: " +zero );
}
//Option three
if (copy2 == 3)
{
loh = 0;
do
{
System.out.println("To check if your number is light or heavy, we need a second interger.");
System.out.print("Please enter a second positive interger: ");
loh = kb.nextInt();
if (loh >= 0)
{
numWeight = ((loh +copy)/2);
//Test num weight
System.out.println("Check: " +numWeight);
if (numWeight > copy)
{
System.out.print("The number " + copy + " compared to the number "
+ loh + " is a heavy number.");
}
else
{
System.out.print("The number " + copy + " compared to the number "
+ loh + " is a light number.");
}
}
if (loh < 0)
{
System.out.println("Error! The number you've entered is not a valid interger.");
}
}while (loh <=0);
}
//Option four
if (copy2 ==4)
{
primeNumbers = 0;
for (int i=1; i<=copy; i++)
{
int counter = 0;
for(int prime = i; prime>=1; prime--)
{
if (i%prime==0)
{
counter = counter +1;
}
}
if (counter==2)
{
primeNumbers = primeNumbers + i;
}
}
System.out.println("Prime numbers from 2-"+copy+" are: ");
System.out.println(primeNumbers);
}
//Option five
else
{
System.out.print("Error! Please enter a valid menu option.");
}
}while (copy2 <0 && copy2 >=6);
}//End main
}//End class
You should use switch case for your purpose. nested if/else isn't good idea for menu options but switch case make it more clear to understand what are you going to do.
switch (num) {
case c1:
statements // they are executed if variable == c1
System.out.println("1. Enter a new number.");
break;
case c2:
System.out.println("2. Print the number of odd digits, even digits, and zeros in the interger.");
statements // they are executed if variable == c2
break;
case c3:
case c4:
statements // they are executed if variable == any of the above c's
break;
. . .
default:
statements // they are executed if none of the above case is satisfied
break;
}

How to keep asking for input while it is in between 0-8 and is not contained in the hash set

I'm having an issue where I want to keep asking the user for input while it is between 0-8, and if it isn't, or if it's already in the hash set, to ask it again.
HashSet<Integer> hash = new HashSet<Integer>(9);
list = new ArrayList<Integer>(9);
System.out.println("\n Enter your own 8-Puzzle Configuration of non-repeating numbers ranging from 0-8.");
int num = 0;
int i = 0;
do {
try {
System.out.println("Enter #" + i + ": ");
num = kb.nextInt();
if (hash.contains(num)) {
System.out
.println("This is number was already entered. Please try again.");
System.out.println("Enter #" + i + ": ");
num = kb.nextInt();
}
if (num <= 0 || num > 8) {
System.out
.println("# must be in the range of 0-8.");
System.out.println("Enter #" + i + ": ");
num = kb.nextInt();
}
list.add(num);
hash.add(num);
i++;
} catch (InputMismatchException e) {
System.out.println("Not a valid number. Try again");
}
kb.nextLine();
} while (i < 9);
You were adding incorrect values if two incorrect values were added in a row. Also, you don't need to use a set - the ArrayList also has a contains method.
ArrayList list = new ArrayList(9);
System.out.println("\n Enter your own 8-Puzzle Configuration of non-repeating numbers ranging from 0-8.");
do {
int index = list.size() + 1;
try {
System.out.println("Enter #" + index + ": ");
int num = kb.nextInt();
if (list.contains(num)) {
System.out
.println("This is number was already entered. Please try again.");
} else if (num <= 0 || num > 8) {
System.out.println("# must be in the range of 0-8.");
} else {
list.add(num);
}
} catch (InputMismatchException e) {
System.out.println("Not a valid number. Try again");
}
} while (list.size() < 8);

printing 2 times donno why

I am having a problem when i break out from remove part the code prints main menu options twice
There is no error in code and it runs properly but why does it print twice instead of once?
public void mainloop() {
for (int i = 0; i < 100; i++) {
String x;
System.out.println("Please Select your option");
System.out.println("............................");
System.out.println("1 ADD NAME AND NUMBER \n2 REMOVE NAME AND NUMBER \n3 SEARCH NAME AND NUMBER \n0 EXIT");
System.out.println("............................");
x = input.nextLine();
if (x.equalsIgnoreCase("0")) {
System.out.println("Thank you!");
break;
}
if (x.equalsIgnoreCase("1")) {
String Name;
String Number;
System.out.println("Please Enter your Name below");
Name = input.nextLine();
System.out.println("Please Enter your Number below");
Number = input.nextLine();
System.out.println("");
System.out.println("Your Name " + Name + " and Number " + Number + " has been saved!\n");
objectclass objectclassObject = new objectclass(Name, Number);
Test.add(objectclassObject);
}
if (x.equalsIgnoreCase("2")) {
System.out.println("-------ALL NAME AND NUMBERS-------");
System.out.println("");
for (int j = 0; j < Test.size();) {
objectclass p = Test.get(j++);
System.out.println(j + ". Name: " + p.getName() + " - " + p.getNumber());
}
for (int j = 0; j < Test.size(); j++) {
System.out.println("");
System.out.println("Enter Index number to remove Contact from Phonebook!");
int v = input.nextInt();
int temp = (v - 1);
if (v >= 1 && v <= Test.size()) {
System.out.println("Name: " + Test.get(temp).getName() + " And Number: " + Test.get(temp).getNumber() + " has been removed!!");
System.out.println("");
Test.remove(temp);
} else {
System.out.println("Please enter number properly!!");
}
break;
}
}
if (x.equalsIgnoreCase("3")) {
String y;
System.out.println("*** Enter your Name below for search ***");
y = input.nextLine();
for (objectclass p : Test) {
String z = p.getName();
if (z.equalsIgnoreCase(y)) {
System.out.println("Your Name is: " + p.getName() + "\nYour Number is: " + p.getNumber());
System.out.println("");
}
if (!z.equalsIgnoreCase(y)) {
System.out.println("Contact not found!!!");
}
}
}
}
}
}
System.out.println("Please Select your option");
System.out.println("............................");
System.out.println("1 ADD NAME AND NUMBER \n2 REMOVE NAME AND NUMBER \n3 SEARCH NAME AND NUMBER \n0 EXIT");
System.out.println("............................");
this prints twice :/~
If this prints twice, you went 2 times thru the loop. Try to display the variable 'x' after reading it. I bet you have extra empty strings between your legitimate input.
What happens is that nextInt() doesn't consume the newline. Therefore, the next time you read x you read the end of the line after the value v.
As mentioned by #Aeshang please use Switch instead of if.
Secondly
if (x.equalsIgnoreCase("2")) {
block does not end before
if (x.equalsIgnoreCase("3")) {
Your remove part also includes search part. Not sure if this will solve the problem but first correct these things and check your answer.

Categories