Page 367 - ComputerScience_Class_11
P. 367

Program 3     Using the concept of an array, input names of 5 students. Input a name to be deleted and
                                 delete the name from the array if found, else provide a suitable message.

                   1      import java.util.Scanner;
                   2      public class DeleteNameFromArray
                   3      {

                   4          public static void main(String[] args)
                   5          {
                   6              Scanner sc = new Scanner(System.in);

                   7              System.out.print("Enter the number of students: ");
                   8              int size = sc.nextInt();
                   9              sc.nextLine();
                  10              String[] students = new String[size];

                  11              System.out.println("Enter the names of " + size + " students:");
                  12              for (int i = 0; i < size; i++) {
                  13                  System.out.print("Student " + (i + 1) + ": ");

                  14                  students[i] = sc.nextLine();
                  15              }
                  16              System.out.print("Enter the name to be deleted: ");
                  17              String nameToDelete = sc.nextLine();

                  18              boolean found = false;
                  19              for (int i = 0; i < size; i++)
                  20              {

                  21                  if (students[i].equals(nameToDelete))
                  22                  {
                  23                      for (int j = i; j < size - 1; j++)
                  24                      {

                  25                          students[j] = students[j + 1];
                  26                      }

                  27                      students[size - 1] = null;
                  28                      found = true;
                  29                      size--;
                  30                      break;

                  31                  }
                  32              }
                  33              if (found)

                  34              {
                  35                  System.out.println("Name '" + nameToDelete + "' has been deleted.");




                                                                                                           Arrays  365
   362   363   364   365   366   367   368   369   370   371   372