问题
Basically I want my code to enable the user to enter x amount of integers (they chose x), then they will then store each of their inputted integer values in my array.
For some reason when I print my array out after all values have been entered:
I get this:
Code:
Scanner input = new Scanner(System.in);
System.out.print("How many integers will you enter:");
int amount = input.nextInt();
int myArray[] = new int[amount];
for (int counter = 0; counter < amount; counter ++){
myArray[counter] = input.nextInt();
}
System.out.println(myArray);
Console:
How many integers will you enter:2
4
2
[I@55f96302
回答1:
Ok, you can take away the for loop and do it this way
System.out.println(Arrays.toString(myArray));
I would strongly recommend to do it with the for loop. It prints one element at the time every time the loop runs, and with your for loop it runs through every element. You need to change the println to this (inside you for loop)
System.out.println(myArray[counter]);
or if you want to have the array on the same line
System.out.print(myArray[counter]+ " ");
Later on when programming you are going to see how useful this is compared to Arrays.toString() method.
回答2:
The string you get is the object notation of array which is expected [I@55f96302
where
[I
is the class name[
one dimentional arrayI
integer array
@
joins the string55f96302
some hash code
To print array do
System.out.println(Arrays.toString(myArray));
or you can simply loop through each element of array
回答3:
You can also use java.util.ArrayList
ArrayList<Integer> myArray = new ArrayList<Integer>(amount);
for (int counter = 0; counter < amount; counter ++){
myArray.add(counter,input.nextInt());
}
System.out.println(myArray);
prints array like this -> [1, 2, 3, 4]
来源:https://stackoverflow.com/questions/29520813/array-printing-java