Java数组运行不正常?

时间:2013-10-27 19:04:45

标签: java arrays for-loop java.util.scanner indexoutofboundsexception

import java.util.Scanner;

public class Maintest {
    static Scanner kb = new Scanner(System.in);
    public static void main (String args[]) {
        System.out.println("This is how you should format your equation => 3.0 x + 5.5 y = 9.0");
        System.out.println("Type your first equation:");
        String first = kb.nextLine();
        //first equation
        Scanner one = new Scanner(first);
        //scanner for first
        double[] arr = new double[6];
        //arr containing numbers
        String[] vars = new String[2];
        //arr containing variable names
        System.out.println("Type your second equation:");
        String second = kb.nextLine();
        //second equations
        Scanner two = new Scanner(second);
        //scanner for second
        one.useDelimiter("[^\\p{Alnum},\\.-]");
        two.useDelimiter("[^\\p{Alnum},\\.-]");
        //anything other than alphanumberic characters,
        //comma, dot or negative sign is skipped
        for (int i = 1; i <= 3; i++) {
            if (one.hasNextDouble())
                arr[i-1] = one.nextDouble();
            else if (one.hasNext())
                vars[i-1] = one.next();
            else if (two.hasNextDouble())
                arr[i+2] = one.nextDouble();
            else if (arr[i-1] == 0.0)
                arr[i-1] = 1.0;
            //putting values into array
        }
        System.out.println(arr[3]);
        System.out.println(vars[2]);
    }
}

我想知道我的代码有什么问题。它应该解决线性方程组,但是现在,我正在研究人们输入的方程中的值。我期望它打印出我告诉它的数组的特定索引的值打印(即arr [3]和vars [2]),但它说java.lang.ArrayIndexOutOfBoundsException:2。请你帮忙,可能告诉我我的错误?哦,我想知道一种更有效的方法来完成相同数量的代码,甚至可以让用户只输入3x + 4.5y = 15而不需要所有不必要的空格或.0。谢谢你的帮助!

1 个答案:

答案 0 :(得分:1)

如您所见,vars是一个第二个数组:

String[] vars = new String[2];

由于Java索引从零开始,这意味着该数组具有两个字符串的“空间”:vars[0]vars[1]。除此之外的任何事情都是越界的,这就是你得到错误的原因:

System.out.println(vars[2]); //vars[2] would be the third String, but vars's length is only two!

您还应该确保在打印语句之前的循环中没有尝试访问vars[2]