gpt4 book ai didi

Java 数组无法正常运行?

转载 作者:行者123 更新时间:2023-12-01 13:56:02 25 4
gpt4 key购买 nike

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

最佳答案

如您所见,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!

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

关于Java 数组无法正常运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19622173/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com