2016-04-14 57 views
0

我正在使用數組添加數字的程序。我已經完成了很多工作,但在最後一部分添加代碼中的實際數字時感到困惑。這是我的代碼。Java,添加數組

public static void main (String[] args) { 
    Scanner input= new Scanner(System.in); 
    System.out.println("Enter size of array"); 
    int n= input.nextInt(); 
    int[] x= new int[n]; 
    System.out.println("Enter Array nums"); 
    for(int i=0;i<n;i++){ 
     x[i]= input.nextInt(); 
    } 
} 
+0

究竟不起作用?你的代碼似乎是正確的。 –

+0

那麼,這是什麼問題? – dambros

+0

***但是我在最後一部分***中感到困惑......它告訴我們如此之好......你究竟得到了什麼以及你期待什麼......? –

回答

1

爲什麼不寫一些代碼來添加數字?

import java.util.Scanner; 
class X { 
    public static void main (String[] args) { 
     Scanner input= new Scanner(System.in); 
     System.out.println("Enter size of array"); 
     int n= input.nextInt(); 
     int[] x= new int[n]; 
     System.out.println("Enter Array nums"); 
     for(int i=0;i<n;i++){ 
      x[i]= input.nextInt(); 
     } 
     int sum = 0; 
     for(int i=0;i<n;i++){ 
      sum+= x[i]; 
     } 
     // to print the result, uncomment the line below 
     //System.out.println(sum); 
    } 
} 
+0

爲什麼不在第一個'for'中做'+ ='? – Andrew

+0

@AndrewTobilko因爲在第一個'for'中不需要添加1以外的數字(在'i ++'中)。 – MikeCAT

+0

@AndrewTobilko非常感謝。這正是我無法理解如何去做的。從來沒有意識到代碼有多簡單,(我推翻了它)。 :) –

1

這裏,將增加你的陣列爲你的方法:你只需要最初以0變量,它具有所有值的總和,然後同時採取輸入

public int totalArray(int[] someArray) { 
    int reply = 0; 
    for (int value : someArray) reply += value; 
    return reply; 
} 
2

值被添加到初始化的變量中,以保持相同for循環中的總值。 下面給出的是相同的代碼。

公共靜態無效的主要(字符串ARGS []){

 Scanner input= new Scanner(System.in); 
     System.out.println("Enter size of array"); 
     int n= input.nextInt(); 
     int[] x= new int[n]; 
     System.out.println("Enter Array nums"); 
     int total=0; 
     for(int i=0;i<n;i++){ 
      x[i]= input.nextInt(); 
      total=total+x[i]; 
     } 
     System.out.println("total"+total); 
}