You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中getOperand方法获取数组大小并填充时遇数组越界异常求助

Hey there! Let's work through your calculator code issues step by step:

1. Fixing the ArrayIndexOutOfBoundsException

The immediate cause of your error is a tiny but critical mistake in your for loop. Arrays in Java are zero-indexed—meaning the first element is at position 0, and the last is at size - 1. Right now, you're trying to assign values to operand[size], which is a position that doesn't exist in your array.

Here's the corrected loop:

for (int x = 0; x < size; x++) {
    operand[x] = input.nextDouble(); // Use x instead of size here
}

2. Returning both array size and the array itself

Java methods can only return a single value, but you don't actually need to return the size separately! Every array has a built-in length property that gives you its size. For example, after getting operand1, you can access its size with operand1.length.

If you really needed to return both values (though it's unnecessary here), you could wrap them in an Object[] (since you can't create new methods/classes), but this is messy. Stick with using the array's length property—it's the cleanest approach.

3. Other small improvements to getOperand

Your method has a few other quirks that can be cleaned up:

  • Prompt order is backwards: You're asking for the array size first, then printing the input prompt after the loop. Users won't know what values to enter until it's too late!
  • Unused parameter: The size parameter you pass to getOperand is immediately overwritten by input.nextInt(), so you can remove it entirely.
  • Scanner reuse: While creating a new Scanner each time works, it's better to create one in your main method and pass it in—but for a beginner project, this is a minor detail.

Here's the revised getOperand method:

public static double[] getOperand(String prompt) {
    Scanner input = new Scanner(System.in);
    System.out.println("Please enter the size for the array");
    int size = input.nextInt();
    double operand[] = new double[size];
    
    // Print the prompt before asking for values
    System.out.println(prompt);
    for (int x = 0; x < size; x++) {
        operand[x] = input.nextDouble();
    }
    return operand;
}

And update your call site to match:

if(selection == 1) {
    double operand1[] = getOperand("Please enter the values for the first array, with a space after each input");
    double operand2[] = getOperand("Please enter the values for the second array, with a space after each input");
    // Pro tip: Make sure your add method checks that both arrays have the same length!
    System.out.println(add(operand1, operand2));
}

内容的提问来源于stack exchange,提问作者Austin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 15:28:14