Comparing elements of ArrayList in loop gives unexpected result?

how to compare elements of an arraylist in java
how to compare two arraylist objects in java
how to compare two arraylist of different objects in java
how to compare elements of an arraylist in java 8
how to compare arraylist elements with string in java
how to compare two arraylist in java and find difference
how to compare two arraylist of different objects in java 8
how to compare two list objects in java

The following code checks only the first item in the ArrayList. When I type in an item that is in the ArrayList but not in the first position, I get my error message as "Please enter a valid name".

How can I fix this? Thank you!

Here is my code:

   private ArrayList<Account> accounts = new ArrayList<>();

   for(Account a : accounts)
    {
        while(true)
        {
            System.out.printf("Customer name: ");
            String customerName = scanner.next();

            if(customerName.equals(a.getName()))
            {
                System.out.println("You entered " + a.getName());
                break;
            }
            else
            {
                System.out.println("Please enter a valid name");
            }
        }
    }   

You have to break from while. When you iterating on list you have to think about logic. Its can be like this code ;

ArrayList<Account> accounts = new ArrayList<>();
boolean isMatched = false;

while (true) {
    for (Account account : accounts) {
        System.out.printf("Customer name: ");
        String customerName = scanner.next();
        if (customerName.equals(account.getName())) {
            isMatched = true;
            break;
        }
    }
    if (isMatched) {
        System.out.println("You entered " + account.getName());
        break;
    }
    System.out.println("Please enter a valid name");
}

PS: boolean value to when found the customer name for ending while loop.

How to compare two ArrayList in Java, We would be using contains() method for comparing two elements of different method and stored the comparison result in third ArrayList ( al3 and al4 ). Yeah i understand while, if and for loops. But im stuck on how to compare the elements within the arraylist. I can't compare the next element with the last, as they may be different. EG: 2 Hearts 3 Spade 2 Hearts 2 Hears. If i compared to last element, it would only get to the end and find 2 matching cards( not the 3 it needs (N -1 (4 - 1)))


The inner loop does do that:

while(true) {

has no purpose here. It simply keeps looping inside the outer loop, therefore always comparing against the same a account!

Basically you have to swap the two loops!

3 Reasons why You Shouldn't Replace Your for-loops by Stream , Here's Angelika's benchmark result on an ordinary loop, finding the max value in a list of boxed ints: ArrayList, for-loop : 6.55 ms ArrayList, seq. ArrayList index starts from 0, so we initialized our index variable i with 0 and looped until it reaches the ArrayList size – 1 index. Inside the loop we print the elements of ArrayList using the get method. Using enhanced for loop. Iterating over ArrayList using enhanced for loop is a bit different from iterating ArrayList using for loop. When we use the enhanced for loop, we do not need to maintain the index variable as given below.


The problem is the infinite while loop.

while(true)

This loop breaks only when customerName == firstElement.Name, else it is an infinite loop. Instead I think what you want to try is moving the while loop outside the for loop. So the code will look something like this.

    private ArrayList<Account> accounts = new ArrayList<>();

    while(true)
    {
        System.out.printf("Customer name: ");
        String customerName = scanner.next();
        for(Account a : accounts){

           if(customerName.equals(a.getName())){
                 System.out.println("You entered " + a.getName());
                 break;
           }else{
            System.out.println("Please enter a valid name");
           }
        }
    }

Avoid ConcurrentModificationException while looping over Java , To give you an example, just loop over a list using for loop and try to remove one of the list, which may affect the progress of iteration and may yield incorrect results. Both Iterator and ListIterator uses this field to detect unexpected change. Problem: loop over an ArrayList and remove selected elements, but remove() is​  Earlier we shared ArrayList example and how to initialize ArrayList in Java. In this post we are sharing how to iterate (loop) ArrayList in Java. Lets have a look at the below example – I have used all of the mentioned methods for iterating list. In the comment section below, Govardhan asked a question: He asked, how to iterate an ArrayList


The problem you have it's because you are only checking the first element all the time. Just after you entering your first element, (and breaking your loop while(1)) you will pass to the second one.

Imagine you have in your arrayList

"hello", "bye"

You'll be inside your loop until texting the first element ("hello").

Solution:

 while(true)
         {
             System.out.printf("Customer name: ");
             String customerName = scanner.next();
             if (accounts.contains(customerName)){
                 System.out.println("You entered " + customerName);
                 break;
             }
             else{
                 System.out.println("Please enter a valid name");
             }
         }

Time To Really Learn Generics: A Java 8 Perspective, List<String> strings = new ArrayList(); Set<Employee> employees = new HashSet(); won't compile // for-each loop knows the contained data type is String for As a result, when you want to store primitives in a generic type, you Java takes care of wrapping the int values inside Integer instances on  Arraylist class implements List interface and it is based on an Array data structure. It is widely used because of the functionality and flexibility it offers. Most of the developers choose Arraylist over Array as it’s a very good alternative of traditional java arrays. ArrayList is a resizable-array implementation of the List interface. It


How Java 8 Lambdas and Streams Can Make Your Code 5 Times , Loops and Iterators vs Lambdas and Streams: How Java 8 lambdas and streams perform The new language features allow us to adopt a more functional style in our code and Honestly, the results were quite surprising. For this benchmark, we've created an ArrayList, populated it with 100,000 random  The following statement creates an ArrayList object. What is the purpose of the <String> notation? ArrayList<String> arr = new ArrayList<String>( ); A. It specifies that only String objects may be stored in the ArrayList object B. It specifies that the get method will return only String objects C.


Building Java Programs 3rd Edition, Self-Check Solutions, The code swaps the values of the variables first and second . Output of loop: correctly by looping over the elements of each array and printing/comparing them one at a Square is a Rectangle and calls setWidth or setHeight on it, unexpected results will occur. Correct syntax to construct an ArrayList to store integers:. You have a tagging interface which suggests you can use this form of for loop:-You will have seen the similarity to a conventional for loop to iterate an array. This only works well if the list is backed by an array. But we know that access to element 123456789 of an array is as fast as access to element 1.


Swift Array Examples, String Arrays, Append to arrays, loop over elements and modify arrays. Print the array contents. print(languages) Output 3 ["Swift", "Python", "Java"] loop. This provides a clear syntax for getting each element in the array. Tip: With constant let arrays, we can enforce code correctness by preventing unexpected changes to the array. Java ArrayList is an ordered collection. It maintains the insertion order of the elements. You cannot create an ArrayList of primitive types like int, char etc. You need to use boxed types like Integer, Character, Boolean etc. Java ArrayList is not synchronized.