【发布时间】:2020-02-09 01:36:27
【问题描述】:
我对 Java 比较陌生,对我的代码为什么不能正常工作感到困惑。我正在使用方法和数组创建一个计算器。在我的代码中,我在下面提供的 getOperand 方法应该首先提示用户输入足够的值来填充数组,然后返回它们的数组。这就是我感到困惑的地方。如果我必须采用相同的方法来检索数组的大小并从用户输入中填充数组,我是否正确设置了数组?两个都可以退货吗?下面我尝试了我认为可行的方法,但它似乎不起作用。当我尝试填充数组时,我得到一个 ArrayIndexOutOfBoundsException
if(selection == 1) {
double operand1[] = getOperand("Please enter the values for the first array, with a space after each input", size);
double operand2[] = getOperand("Please enter the values for the second array, with a space after each input", size);
System.out.println(add(operand1, operand2));
public static double[] getOperand(String prompt, int size) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter the size for the array");
size = input.nextInt();
double operand[] = new double[size];
for (int x = 0; x < size; x++) {
operand[size] = input.nextDouble();
}
// creating new arrays
System.out.println(prompt);
return operand;
我还没有设置其他方法,我首先尝试学习如何让用户输入来填充数组。不幸的是,我也无法添加任何新方法,因为我的方法是为我预定义的。这是方法列表。
public static double[] add(double[] operand1, double[] operand2)
public static double[] subtract(double[] operand1, double[] operand2)
public static double[] multiply(double[] operand1, double[] operand2)
public static double[] divide(double[] operand1, double[] operand2)
public static double[] dotProduct(double[] operand1, double[] operand2)
public static double[] random(double lowerlimit, double upperlimit, int size)
【问题讨论】:
-
这不合逻辑:
int size = getOperand("What size would you like the array", size);为什么要创建一个返回 double 数组的方法并使用它来尝试获取 int 结果? -
如果你用Java声明数组,请使用
double[] operand,而不是double operand[]。第一个被认为是标准的,使用它可以提高任何熟悉 Java 的人的可读性。 -
为什么不包含 add() 函数?
标签: java arrays methods user-input