Answer to Question #309556 in Java | JSP | JSF for Kyle

Question #309556

Write a program to count the number of times a given integer appears in a LL.


1
Expert's answer
2022-03-20T18:44:51-0400
import java.util.LinkedList;
import java.util.Scanner;

public class Test {
    public static Integer findNumberOfElementInLinkedList(LinkedList linkedList, int element) {
        int numberOfOccurrences = 0;
        if (linkedList == null || linkedList.isEmpty()) {
            System.out.println("List is empty");
        }
        else {
            if (linkedList.contains(element)){
                for (int i = 0; i < linkedList.size(); i++){
                    if (element == (int) linkedList.get(i)){
                        numberOfOccurrences++;
                    }
                }
            }
        }
        return numberOfOccurrences;
    }
    public static void main(String args[]){
        Scanner scan = new Scanner(System.in);
        LinkedList<Integer> list = new LinkedList<>();
        System.out.println("Enter number of elements in list: ");
        int numberOfElements = scan.nextInt();
        int numberForSearch;
        System.out.print("Enter elements: ");
        for (int i = 1; i <= numberOfElements; i++){
            list.add(scan.nextInt());
        }
        System.out.println("Enter the number for which you want to count the number of occurrences in the list: ");
        Scanner scanner = new Scanner(System.in);
        numberForSearch = scanner.nextInt();
        System.out.println(list);
        System.out.println("The number of times this item appears in the list - " + findNumberOfElementInLinkedList(list, numberForSearch));
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS