[英]Array Printing Java
基本上,我希望我的代碼使用戶能夠輸入x個整數(他們選擇了x),然后他們會將它們輸入的每個整數值存儲在我的數組中。
由於某些原因,在輸入所有值后打印出數組時:
我得到這個:
碼:
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);
安慰:
How many integers will you enter:2
4
2
[I@55f96302
您獲得的字符串是預期的數組對象表示法[I@55f96302
其中
[I
是班級名稱
[
一維數組 I
整數數組 @
連接字符串 55f96302
一些哈希碼 要打印數組
System.out.println(Arrays.toString(myArray));
或者您可以簡單地遍歷數組的每個元素
好的,您可以取消for循環並以這種方式進行
System.out.println(Arrays.toString(myArray));
我強烈建議使用for循環。 每次循環運行時,它每次都會打印一個元素,而對於您的for循環,它將遍歷每個元素。 您需要將println更改為此(在for循環內部)
System.out.println(myArray[counter]);
或者如果您想將數組放在同一行
System.out.print(myArray[counter]+ " ");
稍后,在進行編程時,您將看到與Arrays.toString()方法相比,該方法有多有用。
您也可以使用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);
這樣打印數組-> [1、2、3、4]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.