3

I've tried couple of things to make this code work, but it didn't. my goal is to instantiate nums[] with numbers {0, 1, 2, .... n-1}. nums has no size, so I used list that instantiate nums with zeros. Keep in mind that the result must be an array (nums).

int nums[] = {}; int n = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number:");
n = scanner.nextInt();

ArrayList<Integer> listNum = new ArrayList<Integer>();
nums = new int[listNum.size()];//instantiate nums with zeros 
//nums = listNum.toArray(nums);
for (int i =0; i < n; i++){
    nums[i] = i;
}
1
  • 3
    Why not create nums after you ask the value for n ? The size will be known at that point. Commented Oct 17, 2015 at 16:48

3 Answers 3

3

When you're writing this :

ArrayList<Integer> listNum = new ArrayList<Integer>();
nums = new int[listNum.size()];//instantiate nums with zeros

listnum has a size of 0, so nums won't be initialized as you want.


Why not just do :

nums = new int[n];

?

Sign up to request clarification or add additional context in comments.

1 Comment

thank you very much, but it means that I don't need to create arraylist . I just want to understand how it works.
3

Array's are fixed in size.

 nums = new int[listNum.size()];

That never works. You are initializing your array with zero elements. Once you declare the array size, you can't change that back.

What you are looking for is

    int nums[] = {}; int n = 0;
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter the number:");
    n = scanner.nextInt();
    nums = new int[n];//instantiate nums with entered size
    for (int i =0; i < n; i++){
        nums[i] = i;
    }

Just get rid of that ArrayList since you are know the size n

Comments

3

You don't need an ArrayList - if you take the input of n from the command line, you could just use it to initialize the array:

nums = new int[n];         
for (int i =0; i < n; i++){
    nums[i] = i;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.