Question

In: Computer Science

Does anyone know how to find if a certain String is available in an ArrayList? I...

Does anyone know how to find if a certain String is available in an ArrayList?

I was asked by my instructor to make a certain program about Student Record

In the area where I need to add some student in the ArrayList it won't add if there is the same name in the ArrayList

at first I used the equals method and contains method but later I found it was prohibited to use such method.

Is there a way to find if a String is Available in the ArrayList without using the method

Please check on else if(response==2)

import java.util.*;
public class performanceTask {

   public static void main(String[] args) {
       int response;
       ArrayList<String> listOfStudent = new ArrayList<String>();

       Scanner aScanner = new Scanner(System.in);
       do {
           System.out.println("[Selection Bar]");
           System.out.println("[1] List of Students.");
           System.out.println("[2] Add Student.");
           System.out.println("[3] Edit Student.");
           System.out.println("[4] Delete Student.");
           System.out.println("[5] Clear list of Students.");
           System.out.println("[6] Exit Program.");
           System.out.println("--------------------------");
           System.out.println("Select an option: ");
           response = aScanner.nextInt();
          
           if(response == 1) {
               int size = listOfStudent.size();
               if(size == 0) {
                   System.out.println("No Records Found!\n");
               } else {
                   Collections.sort(listOfStudent);
                   for(int i = 0; i<listOfStudent.size(); i++) {
                       System.out.println(i + ". " + "[" + listOfStudent.get(i) + "]");
                      
                   }
                   System.out.println("\n");
              
               }
           }else if (response == 2) {
               System.out.println("Enter Name of a Student: ");
               String addStudent = aScanner.next();
              
               if (listOfStudent.contains(addStudent)) {
                   System.out.println(addStudent +" already existed! \n");
                  
               } else {
                   System.out.println("Do you want to save " + addStudent + "? [y/n]: ");
                   String saveIt = aScanner.next();
                       if(saveIt.equals("y") || saveIt.equals("Y") ) {
                           listOfStudent.add(addStudent);
                           System.out.println(addStudent +" has been successfully added! \n ");
                       }else if (saveIt.equals("n") || saveIt.equals("n")) {
                           System.out.println("\n");
                           continue;
                       }else {
                           System.out.println("It must be y or n only!");
                       }
                   }
              

Solutions

Expert Solution

Hi,

Please find the answer below:

To check a duplicate student in the ArrayList without using any inbuilt methods, you need to iterate over the list and see if the student name repeats.

The simple way is to set one flag if the student name is present in the Array list:

boolean foundFlag=false;

// Iterate over the array list

for(String name: listOfStudent)

{

if(name.equalsIgnoreCase(addStudent)){

              foundFlag=true;

              break;

       }

}

if (foundFlag) {

System.out.println(addStudent +" already existed! \n");

-------------------------------------------------------------------------------

Remove the contains code and add the above loop to check existing student name in the

else if(response==2) block.

Other improvements in the code:

Coding standard: Always start the class name with CamelCase letter. For example

PerformanceTask

---------------------------------------------------------

Sample Output:

[Selection Bar]
[1] List of Students.
[2] Add Student.
[3] Edit Student.
[4] Delete Student.
[5] Clear list of Students.
[6] Exit Program.
--------------------------
Select an option:
2
Enter Name of a Student:
John
Do you want to save John? [y/n]:
y
John has been successfully added!

[Selection Bar]
[1] List of Students.
[2] Add Student.
[3] Edit Student.
[4] Delete Student.
[5] Clear list of Students.
[6] Exit Program.
--------------------------
Select an option:
1
0. [John]


[Selection Bar]
[1] List of Students.
[2] Add Student.
[3] Edit Student.
[4] Delete Student.
[5] Clear list of Students.
[6] Exit Program.
--------------------------
Select an option:
2
Enter Name of a Student:
Sarah
Do you want to save Sarah? [y/n]:
y
Sarah has been successfully added!

[Selection Bar]
[1] List of Students.
[2] Add Student.
[3] Edit Student.
[4] Delete Student.
[5] Clear list of Students.
[6] Exit Program.
--------------------------
Select an option:
1
0. [John]
1. [Sarah]


[Selection Bar]
[1] List of Students.
[2] Add Student.
[3] Edit Student.
[4] Delete Student.
[5] Clear list of Students.
[6] Exit Program.
--------------------------
Select an option:
2
Enter Name of a Student:
John
John already existed!

[Selection Bar]
[1] List of Students.
[2] Add Student.
[3] Edit Student.
[4] Delete Student.
[5] Clear list of Students.
[6] Exit Program.
--------------------------
Select an option:

Screenshot:

Let me know if you need further help on this.                      

Hope this helps.


Related Solutions

Does anyone know how to do it on EXCEL? Does anyone know how to do it...
Does anyone know how to do it on EXCEL? Does anyone know how to do it on EXCEL? Does anyone know how to do it on EXCEL? Does anyone know how to do it on EXCEL? Anyone know how to do it on EXCEL? The Statistical Abstract of the United States published by the U.S. Census Bureau reports that the average annual consumption of fresh fruit per person is 99.9 pounds. The standard deviation of fresh fruit consumption is about...
Does anyone know where to find good studies done on theories of gender identity, all I...
Does anyone know where to find good studies done on theories of gender identity, all I keep finding are the actual theories themselves but never a study on the theories.
Does anyone know how to solve this question? I am so lost. Thank you! You are...
Does anyone know how to solve this question? I am so lost. Thank you! You are studying the source of new virus that has recently infected humans. You suspect that the virus was transferred from other primates (they exhibit a similar infection), specifically chimpanzees, gorillas, or orangutans. You sample blood from several infected humans and sequence some viral genes. You then build a phylogenetic tree with the human sequences and all the known strains from each primate. Draw a hypothetical...
Does anyone know how to access altitude and azimuth for different objects on Stellarium?
Does anyone know how to access altitude and azimuth for different objects on Stellarium?
Does anyone know how to do pseudocode on this topic? Write a program to perform the...
Does anyone know how to do pseudocode on this topic? Write a program to perform the following two tasks: 1. The program will accept a string as input in which all of the words are run together, but the first character of each word is uppercase. Convert the string to a string in which the words are separated by spaces and only the first word starts with an uppercase letter. For example, the string "StopAndSmellTheRose" would be converted to "Stop...
Would anyone know how to code this in SQL? I can't quite figure it out. The...
Would anyone know how to code this in SQL? I can't quite figure it out. The following drop command is inserted for convenience so that if you need to recompile your code, it will drop the table DROP TABLE Orders Cascade constraints DROP TABLE OrderLine CASCADE CONSTRAINTS; -- CREATE TABLE Orders ( ordernum INTEGER PRIMARY KEY, priority CHAR(10) NOT NULL, cost INTEGER NOT NULL, /* IC1: The priority is one of: high, medium, or low */ >> /* IC2: The...
since firstN is a string it can't compare to an ArrayList * list so how am i suppose to write these parts comparing the string to the list[mid]
c++ question:int ArrayList::binarySearchID(string firstN) const{   int first = 0;         int last = length - 1;         int mid = (first + last) / 2;   bool found = false;   int index;   while (!found && last >= first)   {       if (firstN == list[mid])       {           found = true;       }       else if (firstN > list[mid])       {           first = mid - 1;       }       else if (firstN < list[mid])       {           last...
With the Taft-Hartley act how does anyone know how much is too much relative to union...
With the Taft-Hartley act how does anyone know how much is too much relative to union dues? What is featherbedding and why is that a problem?
You will then find one human to interview. This can be anyone you know or a...
You will then find one human to interview. This can be anyone you know or a stranger. The interview should be conducted in-person or through skype or FaceTime. The interview should be informal and should focus on any information that you want to learn about your subject. More will be discussed in class about generating interview questions. Try to think of roughly 10 questions to ask your subject. Focus on aspects of the subject’s life, career, family, future aspirations etc.…...
how can i find the number of linear discriminant functions? I need to know how i...
how can i find the number of linear discriminant functions? I need to know how i can find out if there is one function, two functions, more? how do i know how many LDF's are there?
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT