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?
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);
}
}
Comment