是的,这个问题似乎相当容易。 我被要求写一小块代码(Java)的那找出整数数组的替代元素的总和和平均。 起始位置将由用户给出。 例如,如果作为起始位置的用户输入3,总和模块将从索引(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);
}
}
}