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.0。谢谢您的帮助!Java数组运行不正常?

+0

当你在你的debuger中通过你的代码时,你看到了什么? –

回答

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]在打印语句之前的循环。