gpt4 book ai didi

java - 数组的简单 for 循环问题

转载 作者:行者123 更新时间:2023-11-29 07:51:38 24 4
gpt4 key购买 nike

这是我现在的代码

for (int i = 0; i <= listOfPeople.length; i++){
String name = scnr.nextLine();
System.out.println("Person " + (i + 1) + ": ");
listOfPeople[i] = name;
}

人员列表是一个正确声明的字符串列表,其长度为用户发送的值。发生的错误是当我运行程序时,我得到这个:

Person 1: 

Jordan

Person 2:

Jordan

Person 3:

Jordan

Person 4:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at RGG.main(RGG.java:20)

我不太确定哪里出了问题,但我尝试删除 for 循环声明中的 =,然后得到以下输出:

Person 1: 

Jordan

Person 2:

Jordan

Person 3:

第三个提示后,代码继续,我不能在那里输入任何内容。有谁知道会发生什么?提前致谢!

最佳答案

删除 =在这个表达式中 i <= listOfPeople.length; .它导致您访问不存在的数组元素。

for (int i = 0; i < listOfPeople.length; i++){
String name = scnr.nextLine();
System.out.println("Person " + (i) + ": ");
listOfPeople[i] = name;
}

完整示例:

public class PersonArrayTest {

public static void main(String[] args) {
String[] listOfPeople = new String[5];
assign(listOfPeople);
System.out.println(Arrays.toString(listOfPeople));
}

public static void assign(String[] listOfPeople) {

Scanner scnr = new Scanner(System.in);
for (int i = 0; i < listOfPeople.length; i++) {
String name = scnr.nextLine();
System.out.println("Person " + (i) + ": ");
listOfPeople[i] = name;
}
}
}

关于java - 数组的简单 for 循环问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20694610/

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