'Increasing array size
I just started learning java and I'm having a problem in increasing an array's size with a new length provided by the user.
If the user's input is greater than 10 (the initial array's size), then I want to increase the array's size according to the user's input.
This is done within the checkFull(int, int) method, however after copying the newArray in articles the size is still 10.
Am I doing it completely wrong?
int[][] articles = new int[10][3];
public static int[][] checkFull(int[][] articles, int noOfArticles) {
System.out.print("Ange antal nya artiklar: ");
int noOfNewArticles = input();
if (noOfNewArticles > 10) {
int[][] newArray = Arrays.copyOf(articles, articles.length + (noOfNewArticles - articles.length));
articles = Arrays.copyOf(newArray, newArray.length);
}
return articles;
}
Solution 1:[1]
articles.length + (noOfNewArticles - articles.length) is just noOfNewArticles. You also never use noOfArticles, so I changed it to noOfNewArticles.
I tried simplifying your code, and it worked fine for me:
public static int[][] checkFull(int[][] articles, int noOfNewArticles) {
if (noOfNewArticles > 10) {
return Arrays.copyOf(articles, noOfNewArticles);
}
return articles;
}
When I run
int[][] articles = new int[10][3];
for (int i = 0; i<20;i++){
System.out.println((checkFull(articles, i)).length);
}
I get
10
10
10
10
10
10
10
10
10
10
10
11
12
13
14
15
16
17
18
19
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jhanzaib Humayun |
