2016-11-24 54 views
0

我想創建一個循環,要求掃描器在數組中以一定數量輸入每個數字(我在考慮10)。有什麼建議麼?爲陣列掃描器創建一個循環

import java.util.Scanner; 

public class AssignSeven 
{ 
    public static void main(String[] args) 
    { 
     int [] array1 = new int[10]; 
     System.out.println("Enter 10 numbers"); 
     Scanner sc = new Scanner(System.in); 
     int a = sc.nextInt(); 

     for (int i = 0; i < 9; i++) 
     { 
      array1[i] = a; 
     } 

    } 
} 
+0

你只要求輸入一次。 – Carcigenicate

+0

它應該是'array1 [i] = sc.nextInt();' – Saravana

回答

1

變化

for (int i = 0; i < 9; i++) 
    { 
     int a = sc.nextInt(); 
     array1[i] = a; 
    } 

甚至

for (int i = 0; i < 9; i++) 
    { 
     array1[i] = sc.nextInt(); 
    } 
+0

謝謝!我看到出了什麼問題 –

0

這很簡單,你可以掃描對象的輸入值只分配給數組的索引:

import java.util.Scanner; 

public class AssignSeven 
{ 
    public static void main(String[] args) 
    { 
     int [] array1 = new int[10]; 
     System.out.println("Enter 10 numbers"); 
     Scanner sc = new Scanner(System.in); 

     // Where you had the original input 
     // int a = sc.nextInt(); 

     for (int i = 0; i < 9; i++) 
     { 
      // Instead of array1[i] = a; you have 
      array1[i] = sc.nextInt(); 
     } 

    } 
} 

希望這有助於!

+0

謝謝!我明白了什麼是錯的! –