当我编写此代码来提示用户要输入多少个数字时,我收到一条错误消息:“线程主 java.lang.arrayindexoutofboundsexception 中出现异常”
PS:注意我是用int数组+for循环来写的。
import java.util.*;
public class Pr8{
public static void main(String[] args){
Scanner scan = new Scanner (System.in);
//Prompt the user for how many numbers are going to be entered.
System.out.print("*Please write how many numbers are going to be entered: ");
int a = scan.nextInt();
int[] n = new int[a];
for (int i = 0; i < a; i++){
System.out.print("*Please enter an enteger: ");
n[a] = scan.nextInt();
}//for
}//main
}//Pr8
最佳答案
改变
n[a] = scan.nextInt();
至
n[i] = scan.nextInt();
a
不是仅包含 a
元素的数组中的有效索引。有效索引为 0 到 a-1。
关于java - 使用数组+for循环时为"exception in thread main java.lang.arrayindexoutofboundsexception",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26801877/