468,294 Members | 1,961 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,294 developers. It's quick & easy.

How do I create a user defined array size?

I'm trying to create a program that prompts the user for a number N. This number will be used to prompt the user N times to provide an integer.
Apr 27 '13 #1
2 32704
game2d
59
Expand|Select|Wrap|Line Numbers
  1.  
  2. Scanner sc = new Scanner();
  3.  
  4. System.out.println("Enter size of your array");
  5. int n = sc.nextInt();
  6.  
  7. int a[] = new int[n];
  8.  
  9. System.out.println("Enter values);
  10. for(int i = 0; i < a.length; i++)
  11. {
  12.   a[i] = nextInt();
  13. }
Apr 28 '13 #2
Sherin
77 64KB
Try This Code

Expand|Select|Wrap|Line Numbers
  1. import java.util.Arrays;
  2. import java.util.Scanner;
  3.  
  4. public class PopulatingAnArray {
  5.    public static void main(String args[]) {
  6.       System.out.println("Enter the required size of the array :: ");
  7.       Scanner s = new Scanner(System.in);
  8.       int size = s.nextInt();
  9.       int myArray[] = new int [size];
  10.       System.out.println("Enter the elements of the array one by one ");
  11.  
  12.       for(int i = 0; i<size; i++) {
  13.          myArray[i] = s.nextInt();
  14.      }
  15.      System.out.println("Contents of the array are: "+Arrays.toString(myArray));
  16.    }
  17. }
Feb 11 '21 #3

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

4 posts views Thread by Bilgehan.Balban | last post: by
4 posts views Thread by robert.waters | last post: by
reply views Thread by Teichintx | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.