java - Dropping the first or last index from an array without getting an "Out of Bounds" Error -


i've been assigned create program in 1 of methods have prompt user input index drop value of. problem when try drop index 0 arrayindexoutofboundsexception @ index -1. fix tried i <= currentsize + 1 fixed index 0 problem, last index out of bounds error because currentsize 1 more array size. appreciated.

//this method drops value of selected index in array. private static void drop () {      int m =0;      system.out.println("choose index drop value of:");          if(input.hasnextint())      {          m = input.nextint();          for(int pos = 0; pos < values.length; pos++)          {              if(pos == m)              {                  for(int = pos+1; i<=currentsize+1; i++)                  {                      values[i-1]= values[i];                      values[i]=0;                  }                  currentsize--;                  break;              }              else if(pos == 0)              {                  system.out.println("error: there not index @ specified location.");              }            }      }      else      {          system.out.println("error: please input integer value.");      } } 

here's efficient , compact way it:

private static void drop(int[] arr, int index, int currentsize) {     system.arraycopy(arr, index + 1, arr, index, currentsize - index - 1); } 

this shifts array elements left, starting specified index + 1 until currentsize. works valid index, example array of size 3, works indexes 0, 1, 2. doesn't check boundaries, in example index -1 or 3 throw arrayindexoutofboundsexception.

using function, simplify code to:

private static void maininputloop() {     system.out.println("choose index drop value of:");     if (input.hasnextint()) {         index = input.nextint();         drop(values, index, currentsize--);     } else {         system.out.println("error: please input integer value.");     } } 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -