Showing posts with label Create Run Time Array Size. Show all posts
Showing posts with label Create Run Time Array Size. Show all posts

Tuesday, 5 August 2014

Write a Program in Java which create array size according to user input value

Structure of the Problem Requirements 


In this problem we will learn how to create Array at run time . The program will asked user to enter the value of the array size which you want to create. After this the program will receive the values from the user . Here is the solution which help you to better understand .


Source Code


package com.ancodingpoint.www;

import java.util.Scanner;
public class Array_Size
{
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
int size;
System.out.print("\nEnter Size of Array: ");
size=input.nextInt();

int[] myArray=new int[size];

for(int i=0;i<size;i++)
{
System.out.print("Enter Value "+(i+1)+": ");
myArray[i]=input.nextInt();
}
myArray=zeroMax(myArray,size);
for(int i=0;i<size;i++)
{
System.out.print(myArray[i]+", ");
}
}

public static int[] zeroMax(int[] myArray, int size)
{
for(int i=0;i<size;i++)
{
if(myArray[i]==0)
{
if((i+1)<size)
{
if(myArray[(i+1)]%2==0 && myArray[(i+1)]!=0)
{
myArray[i]=myArray[(i+1)]-1;
}
else if(myArray[(i+1)]%2==1)
{
myArray[i]=myArray[(i+1)];
}
else
{
myArray[i]=0;
}
}
}
}
return myArray;
}
}

Outout of the Program

Java Array Programming
Java Array Programming