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;
}
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];
?
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
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.