您看到的第一个for循环未执行,我不确定为什么。它被完全忽略了,我在一个单独的方法中尝试了它,然后在main方法中尝试了它,但是似乎有些忽略,但是我不确定如何运行它,它只是转到了main中运行的下一个方法方法。

package math;
import java.util.Scanner;


public class mathAverageValue {

    static int numOfVals;
    static double total;
    static double average;
    static double[] arr = new double[numOfVals];
    static String boole;

    public static void input() {
        Scanner s = new Scanner(System.in);
        System.out.println("How many values will be averaged ? : ");
        numOfVals = s.nextInt();
        for(int i=0; i<arr.length; i++){
                System.out.print("Enter Element No."+(i+1)+": ");
                arr[i] = s.nextDouble();
        }
    }


    public static void process() {
        for (int i=0; i < arr.length; i++) {
            total = total + arr[i];
        }

        average = total / arr.length;
    }

    public static void output() {

        System.out.println("Your average is : " + average);

        System.out.println("Would you like to average again? Y or N : ");
        Scanner i = new Scanner(System.in);
        boole = i.next();

        if ("Y".equals(boole)) {
            input();
            output();
        }
    }

    public static void main(String[] args) {
        input();
        output();
    }

}

最佳答案

问题是您已经为numOfVals分配了一个值,然后以错误的顺序创建了数组。

public static void input() {
    Scanner s = new Scanner(System.in);
    System.out.println("How many values will be averaged ? : ");
    numOfVals = s.nextInt();
    arr = new double[numOfVals];       // <-- PUT THIS HERE
    for(int i=0; i<arr.length; i++){
            System.out.print("Enter Element No."+(i+1)+": ");
            arr[i] = s.nextDouble();
    }
}

关于java - Java for循环未执行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49089377/

10-11 18:05