问题
I wrote a class that has a 2d array. The class will print out the numbers of an array based on user input and size. For example the user input will be like 2 3 145464. This means that the array size is 2 rows and 3 columns and it should print the numbers in the array as
145
464
I cant figure out how to get the size of the array to change without declaring the size originally .
This is what i wrote
import java.util.Scanner;
public class Assignment7
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int [][] nums = new int[scan.nextInt()][scan.nextInt()];
System.out.print("Enter numbers of an array ");
for (int i = 0; i < nums.length; ++i)
{
for (int j = 0; j < nums.length; ++j)
{
nums[i][j] = scan.nextInt();
}
}
for (int i = 0; i < nums.length; ++i)
{
System.out.print("\n");
for (int j = 0; j < nums.length; ++j)
{
System.out.print(nums[i][j]);
}
}
}
}
回答1:
Take a look at using an ArrayList, see http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html or Vector if you need a synchronized list, see http://docs.oracle.com/javase/6/docs/api/java/util/Vector.html
I cant figure out how to get the size of the array to change without declaring the size originally .
There are methods on this generic class that allow you to add/remove elements as you please. Furthermore, you will not have to declare the size of your arraylist before hand.
Example
ArrayList<String> listOfString = new ArrayList<String>();
listOfString.add("foo");
listOfString.add("bar");
ArrayList<Integer> listOfInts = new ArrayList<Integer>();
listOfInts.add(1);
listOfInts.add(2);
There are methods that will allow you to return the size as well as being able to iterate through to perform required actions. See the javadocs if you want to find out more!
It seems like you're using a multidimensional array
; in this case, you can simply place an ArrayList
as the generic type of the original ArrayList
. Remember that you can't use primitives as generic types
though, so for int
, you would need to use Integer
Further Information
It's useful to note that the List interface is available which both Vector/ArrayList/LinkedList/etc implement; see http://docs.oracle.com/javase/6/docs/api/java/util/List.html
回答2:
You are better off using lists in order to archive this as they don't have to maintain a fixed size from initialization. Lists are much easier to use, and have much more functionality. You can dynamically remove items without having to reorder them to avoid having empty spaces, etc.
来源:https://stackoverflow.com/questions/16221887/growing-the-size-of-an-array-based-on-issue-input