循环数组以存储使用前一个元素的值

时间:2014-12-16 01:41:02

标签: java arrays loops

我试图循环一个数组,以便它根据等式存储一个数字。在等式中使用下一个元素的位置。 (对不起,如果这不能解释得太好)但这是一个例子。 A = 10-1,B = A-1,C = B-1。希望能把它搞清楚。

 BufferedReader br = new BufferedReader
                       (new InputStreamReader(System.in));
    int tryAgain =1;
    double[]arrayYear = new double[41];
    System.out.println("DECLINING ATTENDANCE");
    System.out.println("=====================");
    System.out.println("Attendance has been decreasing steadily at weekly religious services from\n1985. This program will dislpay the percentage of the Canadian population that\nattends a weekly religious service, from any year from 1985-2025.");
    for (int i = 0; i <=40; i ++){
        arrayYear[i] = 30-0.45;}

2 个答案:

答案 0 :(得分:1)

arrayYear[i] = 30 - 0.45 * i;

或者,为了更准确:

arrayYear[i] = 30 - 45 * i / 100.0;

答案 1 :(得分:0)

您可以使用arrayYear[i-1]访问之前的值。但请注意,因为如果从i = 0开始,您将在数组中请求不存在的元素-1。您可以通过将第一个值设置为9并从i = 1开始来规避这一点:

arrayYear[0] = 9;

for (int i = 1; i <= 40; i++)
    arrayYear[i] = arrayYear[i-1]-1;