Insert a number at a specified position

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • shashankraj1231
    New Member
    • May 2010
    • 13

    #1

    Insert a number at a specified position

    I am trying to write a program in which i can insert a given number, taken as a input from the user, in a array, provided by the user at a position of the user's choice, but i am not able to do that. Please let me know what i am doing wrong.

    Also, I am trying to achieve that using two arrays. Is there a possibility to achieve the same result using just one parent array?


    Code:
    import java.io.*;
    
    public class findnum {
    	public static void main(String[] args) throws IOException
    	{
           int arr[]= new int[100];
           int arr2[]=new int[100];
           String s1= new String();
           Integer loc= new Integer(0);
           Integer insert= new Integer(0);
           int i=0;
           BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
           System.out.println("Enteger the Elements of the array, -1 to quit: ");
    	   System.out.flush();
    	   for( i=0; ;i++)
    	   {
    		   s1=br.readLine();
    		   if((Integer.valueOf(s1))==-1)
    			   break;
    		   arr[i]=Integer.valueOf(s1);
    
    	   }
    	   System.out.println("Total = "+" "+i);
    	   System.out.println("Enter the location to insert a number :");
    	   System.out.flush();
    	   s1=br.readLine();
    	   loc=Integer.valueOf(s1);
    	   System.out.println("Enter the element to add: ");
    	   s1= br.readLine();
    	   insert= Integer.valueOf(s1);
    	    for(int j=0;j<=i ;j++)
    	    {
                    if (j==loc-1)
                    {
                    int temp = arr[j];
                    arr2[j]=insert;
                    arr2[j++]=temp;
                    //j++;
                    }else
                   arr2[j]=arr[j];
               }
               //arr2[loc]=insert;
                
               for(int temp=0;temp<50;temp++)
                   System.out.print("-");
               System.out.println(" ");
              for(int j:arr2)
    	    System.out.println(j);
    	}
    }
    Last edited by Niheel; May 31 '10, 04:33 AM. Reason: added code tags
  • jkmyoung
    Recognized Expert Top Contributor
    • Mar 2006
    • 2057

    #2
    Yes. Instead of starting from the front, start from the back of the array. If you insert a number into a position, all the other numbers before that point must be bumped forward first. Then insert your number in the gap you've created. The rest of the numbers can stay in the same spot.

    Comment

    • shashankraj1231
      New Member
      • May 2010
      • 13

      #3
      Thanks for the reply. Let me try that and see how it goes.

      Comment

      Working...