In: Computer Science
create a public class and a main class to
deletebyStudentID number with get ID and getStudentByName in public
class. when the user is prompted to search for the student and
delete them by their. ID has seven digits and 6 students
each.
Ex. Delete student by their ID
Enter students name and
their ID
Vanessa,
1111-111
Vanessa is now
deleted
Solution :
Steps :
1.Create Model class for student with name and id in it
2.Make getter and setter for studentId and studentName;
3 .In main class declare arraylist for student class and add them in student arraylist.
4.ask user for name and id.
5 . use if loop for matching the student details.
Java Class for Student :
public class Students
{
/* public constructor for Student */
public Students (String studentId, String studentName)
{
this.studentId = studentId;
this.studentName = studentName;
}
/* getter and setter for student */
public String getStudentId ()
{
return studentId;
}
public String getStudentName ()
{
return studentName;
}
/* declaring the private variable for student name and
student id*/
private String studentId;
private String studentName;
}
Main Class :
import java.util.ArrayList;
import java.util.Scanner;
/* creating main class*/
public class Main
{
public static void main (String[]args)
{
/* declaring the student arraylist for storing the student data
*/
ArrayList < Students > students = new ArrayList <>
();
/* adding student data in the form of student object */
Students s = new Students ("11", "Student1");
Students s1 = new Students ("1111-111", "Vanessa");
Students s2 = new Students ("111", "Student2");
Students s3 = new Students ("1111", "Student3");
Students s4 = new Students ("11111", "Student4");
/* adding student data in thr arraylist */
students.add (s);
students.add (s1);
students.add (s2);
students.add (s3);
students.add (s4);
System.out.println ("Enter students name and their ID");
Scanner sc = new Scanner (System.in);
/* taking input from the user to delete the student details
*/
String name = sc.nextLine ();
String id = sc.nextLine ();
/* using the temporary variable for checking that record is deleted
or not */
int temp = 0;
for (int i = 0; i < students.size (); i++)
{
/* checking that details is matched with the inserted
student details */
if (students.get (i).getStudentId ().equals (id)
&& students.get (i).getStudentName ().equals
(name))
{
/* if found simply remove the student data from
arraylist */
students.remove (i);
System.out.println (name + " is now deleted");
//changing the temporary varianble value
temp = 1;
break;
}
}
/* if no student is found with that name and id */
if (temp == 0)
System.out.println ("NO record found");
}
}
Code ScreenShot :
Output ScreenShots :