fayimora

Remove am item from an aray constructively

Jun 28th, 2011
257
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.00 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. class UseArrays
  4. // Demonstrates a method which removes the last item from an array
  5. {
  6.  public static void main(String[] args) throws Exception
  7.  {
  8.       Scanner input = new Scanner(System.in);
  9.       System.out.println("Enter some numbers (all on one line, separated by spaces):");
  10.       String line = input.nextLine();
  11.       String[] numbers = line.split(" +");
  12.       int[] a = new int[numbers.length];
  13.      
  14.      for(int i=0; i<a.length; i++)
  15.           a[i]=Integer.parseInt(numbers[i]);
  16.      
  17.    
  18.       System.out.println("The numbers are stored in an array");
  19.       System.out.println("The array is");
  20.      
  21.       System.out.println(Arrays.toString(a));
  22.       int[] b = remove(a);
  23.      
  24.       System.out.println("The array obtained by removing the last item is");
  25.       System.out.println(Arrays.toString(b));
  26.       System.out.println("The original array is still");
  27.      
  28.       System.out.println(Arrays.toString(a));
  29.  }
  30.  
  31.  public static int[] remove(int[] a)
  32.  {
  33.     int[] b = new int[a.length-1];
  34.         for(int i=0; i<a.length-1; i++)
  35.             b[i]=a[i];
  36.     return b;
  37. }
  38.  
  39. }
Advertisement
Add Comment
Please, Sign In to add comment