2017-05-24 26 views
0

我想獲取字符串和整數的值,所以我可以利用它。我已經採取了價值,並試圖存儲在數組中,然後打印該值。出於某種原因,我沒有正確地獲取字符串的值。你能幫我把我的代碼改正嗎?字符串數組沒有得到正確的值

public static void main(String[] args) { 
     Scanner sc = new Scanner(System.in); 
     int r = sc.nextInt(); 
     int [] numbers = new int[r]; 
     String names[] = new String[r]; 
     for(int i=0; i<r; i++){ 
      numbers[i] += sc.nextInt(); 
      names[i] += sc.next(); 
     } 
     System.out.println(Arrays.toString(numbers)); 
     System.out.println(Arrays.toString(names)); 
    } 

Output : [2,2] 
     [nullAA, nullBB] 

而且如何獲得打印語句後兩個數組的索引。

回答

3

將缺省值names[i](空)附加到從Scanner中讀取的值中。

變化

names[i] += sc.next(); 

names[i] = sc.next(); 

如果你要打印的數組的索引,使用一個循環:

for (int i = 0; i < r; i++) 
    System.out.print(i + " "); 
System.out.println(); 
+0

由於其工作正常。我需要一個循環來獲取索引或其他方式也存在 –

+0

@shankysingh是的,請參閱編輯。 – Eran

+0

謝謝。因此,我是初學者,有點混亂。 10分鐘後我會接受答案。再次感謝。 –

相關問題