Answers for "Remove element from a specific index from an array in java"

1

Java program to delete specified integer from an array

// Java program to delete specified integer from an array
import java.util.Scanner;
public class DeleteSpecifiedInteger
{
   public static void main(String[] args)
   {
      int num, n, temp = 1, place = 0;
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter number of elements: ");
      num = sc.nextInt();
      int[] arrNum = new int[num];
      System.out.println("Please enter all the elements: ");
      for(int a = 0; a < num; a++)
      {
         arrNum[a] = sc.nextInt();
      }
      System.out.println("Enter the element you want to delete: ");
      n = sc.nextInt();
      for(int a = 0; a < num; a++)
      {
         if(arrNum[a] == n)
         {
            temp = 1;
            place = a;
            break;
         }
         else
         {
            temp = 0;
         }
      }
      if(temp == 1)
      {
         for(int a = place + 1; a < num; a++)
         {
            arrNum[a - 1] = arrNum[a];
         }
         System.out.println("After deleting element: ");
         for(int a = 0; a < num - 2; a++)
         {
            System.out.print(arrNum[a] + ",");
         }
         System.out.print(arrNum[num - 2]);
      }
      else
      {
         System.out.println("Element not found!!");
      }
      sc.close();
   }
}
Posted by: Guest on December-23-2020
1

Remove element from a specific index from an array in java

// remove element from a specific index from an array
import java.util.Arrays;
public class DeleteElementDemo
{
   // remove element method 
   public static int[] removeElement(int[] arrGiven, int index) 
   {
      // if empty 
      if(arrGiven == null || index < 0 || index >= arrGiven.length) 
      {
         return arrGiven; 
      }
      // creating another array one less than initial array 
      int[] newArray = new int[arrGiven.length - 1];
      // copying elements except index 
      for(int a = 0, b = 0; a < arrGiven.length; a++) 
      { 
         if(a == index)
         {
            continue;
         }
         newArray[b++] = arrGiven[a]; 
      }
      return newArray; 
   }
   public static void main(String[] args) 
   { 
      int[] arrInput = { 2, 4, 6, 8, 10 };
      // printing given array 
      System.out.println("Given array: " + Arrays.toString(arrInput));
      // getting specified index 
      int index = 3;
      // print index 
      System.out.println("Index to be removed: " + index);
      // removing element 
      arrInput = removeElement(arrInput, index);
      // printing new array 
      System.out.println("New array: " + Arrays.toString(arrInput));
   }
}
Posted by: Guest on February-18-2021

Code answers related to "Remove element from a specific index from an array in java"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language