Java数组输出边界无法找到超出范围的索引

时间:2014-08-20 08:10:55

标签: java arrays loops

这是一个eulers方法程序,我想我差点搞定了,但是我一直得到我的x和y数组之间的arrayIndex和它的计数器i,我想我知道arrayIndex超出界限是什么意思但我不能似乎得到了指数超出界限的地方。有人可以帮忙吗?

import java.util.Scanner;
import static java.lang.System.out;
import static java.lang.System.in;

public class INFINITE_EULER {

    /**
     * @param args
     */
    public static float functionof(float b,float c){
        return (float) ((float) Math.pow(b+0.1, 2)+ Math.pow(c+0.1, 2)); //to return the function of x and y 
    }

    public static void main(String[] args) {
        Scanner myScanner = new Scanner(in);
        out.println("Programme to implement Eulers method");
        float h;

        float y[] = new float[100]; //initialize the value of x from 0 to 100
        float x[] = new float[100]; // initialize the value of y from 0 to 100
        int i; //variable i is the counter for the array
        out.println("enter the value of h");
        h = myScanner.nextFloat();
        out.println("Enter the first and second interval");
        x[0]=myScanner.nextFloat(); //take the value of x0
        y[0]=myScanner.nextFloat(); //take the value of y0

        for(i = 0 ; i < 100 ; i ++);{ // for x0 to x100 
            y[i+1] = y[i] + h * Math.abs(functionof(x[i],y[i])); //do yi+1 = yi + h * function of current x and current y through the loop
            out.print("y");
            out.print(i);
            out.print("=");
            out.print(y[i]);
        }
    }
}

1 个答案:

答案 0 :(得分:2)

你的问题: 在

  y[i+1] = y[i] + h * Math.abs(functionof(x[i],y[i])); //do yi+1 = yi + h * function of current x    and  current y through the loop
循环时

for(i = 0 ; i < 100 ; i ++)

表示

 for(i=0 to 99) 
 y[i+1] -- > when i=99, you will try to acess y[99+1] i.e, y[100] that doesn't exist

编辑: 将您的代码更改为:

for(i = 1 ; i < 100 ; i ++){ // for x1 to x99
        y[i] = y[i-1] + h * Math.abs(functionof(x[i-1],y[i-1])); 
        out.print("y");
        out.print(i-1);
        out.print("=");
        out.print(y[i-1]);
}