整数数组的替代元素之和

时间:2015-01-07 13:27:46

标签: java arrays sum

是的,问题似乎很容易。我被要求写一小段代码(Java),找出整数数组的替代元素的总和和平均值。起始位置将由用户给出。例如,如果用户输入3作为起始位置,则sum模块将从索引(3-1 = 2)开始。我的目标是不完成我的作业或东西,但要了解为什么我的代码不起作用。所以,如果有人能指出请并建议修复?这是代码:

import java.util.Scanner;
public class Program {

static int ar[]; static int sum = 0; static double avg = 0.0;
static Scanner sc = new Scanner(System.in);
public Program(int s){
    ar = new int[s];
}
void accept(){
    for (int i = 0; i<ar.length; i++){
        System.out.println("Enter value of ar["+i+"] : ");
        ar[i] = sc.nextInt();
    }
}
void calc(int pos){
    for (int i = (pos-1); i<ar.length; i+=2){
        sum = ar[i] + ar[i+1];
    }
}
public static void main(String[] args){
    boolean run = true;
    while (run){
    System.out.println("Enter the size of the array: ");
    int size = sc.nextInt(); 
    Program a = new Program(size);
    a.accept(); 
    System.out.println("Enter starting position: "); int pos = sc.nextInt(); //Accept position
    if (pos<0 || pos>ar.length){
        System.out.println("ERROR: Restart operations");
        run = true;
    }
    a.calc(pos); //Index = pos - 1; 
    run = false; avg = sum/ar.length;
    System.out.println("The sum of alternate elements is: " + sum + "\n and their average is: " + avg); 

   }
 }
}

1 个答案:

答案 0 :(得分:0)

在你的calc方法中,你得到了for循环定义(即初始值,条件和增量都是正确的),但在循环内,sum计算错误。在每次迭代中,您应该将当前元素 - ar[i] - 添加到总sum

for (int i = (pos-1); i<ar.length; i+=2){
    sum = sum + ar[i]; // or sum += ar[i];
}

平均计算中也有错误:

avg = sum/ar.length;

如果平均值在所有元素上,则这只是正确的。由于平均值是元素的一半,因此不应除以ar.length