2017-09-25 86 views
-2

我想要實現的是:用掃描儀輸入數組,現在不能打印數組?

  1. 創建一個數組,並定義其與用戶輸入(掃描儀)的長度。 ✓
  2. 循環遍歷數組以填充其值。 ✓
  3. 定義其長度並根據長度填充值後,打印整個陣列。 X

我無法達到第3位。有人可以幫我嗎?我只需要打印數組。

這是我的代碼:

package arrayinputoutput; 

import java.util.Scanner; 

public class ArrayInputOutput { 

    public static void main(String[] args) { 
     Scanner input = new Scanner(System.in); 
     int x; 
     int[] test; 

     System.out.println("How long should the array be?"); 
     x = input.nextInt(); 

     for (int i = 0; i < x + 1; i++) { 
      input.nextLine(); 
      System.out.println("Please fill in position " + i + ":"); 
      i = input.nextInt(); 

     } 
     //System.out.println(test[]); 
    } 
} 
+0

但是你沒有填滿陣列!在讀取每個值時,必須在每個索引上填充數組。 –

+0

@RenatoAfonso這不是真正的問題;這段代碼甚至沒有編譯。 – progyammer

+0

@progyammer首先從你認爲它不能編譯的東西來看?它只編譯FINE。 –

回答

2
  • 要求尺寸後,喲必須創建array,與大小
  • ,你必須輸入存儲在陣列myArray[i] = input.nextInt();的框,然後跳行
  • 請使用明確的名稱variables
  • 停止size而不是size+1因爲指標STA RT至0

所以這樣的:

int size; 
int[] myArray; 
System.out.println("How long should the array be?"); 
size = input.nextInt(); 
input.nextLine(); 
myArray= new int[size];      //<- create array 

for (int i = 0; i < size ; i++) {   // <- '<size' and '<size+1' 
    System.out.println("Please fill in position " + i + ":"); 
    myArray[i] = input.nextInt();   // <- store in a box of the array 
    input.nextLine(); 
} 

要打印陣列,幾個選項,如:

OR:

for (int i = 0; i < size ; i++) {   
    System.out.println("Value in position " + i + ":" + myArray[i]);  
} 
+0

我必須做Size + 1,因爲如果我輸入一個數組長度爲5的數據,它只會詢問4.這就是爲什麼。 –

+0

@DenizYildiz肯定,但你開始0,這就是數組的工作原理,看這裏[文檔](https://docs.oracle.com/javase/specs/jls/se8/html/jls-10.html#jls-10.4 )如果你設置大小+ 1,你將有OutOfBoundsException – azro

0

System.out.println(Arrays.toString(test));

嘗試使用它來打印數組..希望它的工作原理