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
sizeparameter you pass togetOperandis immediately overwritten byinput.nextInt(), so you can remove it entirely. - Scanner reuse: While creating a new
Scannereach 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

