0
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。谢谢您的帮助!

4

1 回答 1

1

如您所见,vars是一个大小为 2 的数组:

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]在 print 语句之前的循环中访问。

于 2013-10-27T19:10:09.130 回答