英文:
How to add a new record in java?
问题
主程序:
System.out.print("输入新学生姓名:");
String studName = input.nextLine();
newCourse.addStudent(studName);
类:
public void addStudent(String studName){
studentNames[noOfStudents] = studName;
noOfStudents++;
}
运行后显示如下错误:
异常信息:Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
英文:
Main program:
System.out.print("Enter the new student name: ");
String studName = input.nextLine();
newCourse.addStudent(studName);
class:
public void addStudent(String studName){
studentNames[noOfStudents] = studName;
noOfStudents++;
}
After run it show me this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
答案1
得分: 1
如果您想使用数组,由于它不可扩展,您需要创建一个比原数组多一个索引的基础副本,以将所需的元素放入其中。
以下示例使用自定义方法来实现:
public static void main(String[] args) {
final int[] start = {1, 7, -4},
added = append(start, 77);
System.out.println("added: " + Arrays.toString(added));
}
static public int[] append(final int[] values, final int newValue) {
final int[] result = Arrays.copyOf(values, values.length + 1);
result[values.length] = newValue;
return result;
}
英文:
If you want to use an Array, since its not expendable, you need to creat a copy of the underlying Array with one more index than the original one to put the wanted element in it.
This example uses an own method to do so:
public static void main(String[] args) {
final int [] start = {1,7,-4},
added = append(start, 77);
System.out.println("added: " + Arrays.toString(added));
}
static public int[] append(final int[] values, final int newValue) {
final int[] result = Arrays.copyOf(values, values.length + 1);
result[values.length] = newValue;
return result;}
答案2
得分: 0
使用数组进行诸如添加/移除之类的操作并不推荐。
开始使用列表将会让你的生活更加轻松。
以下是使用列表的示例:
List<String> students = new ArrayList<>();
System.out.print("输入新学生的姓名:");
String studentName = input.nextLine();
students.add(studentName);
System.out.println("学生人数:" + students.size());
英文:
Using arrays for operations like add/remove is not recommended.
Start using lists will make your life easier.
Following your example with lists
List<String> students = new ArrayList<>();
System.out.print("Enter the new student name: ");
String studentName = input.nextLine();
students.add(studentName);
System.out.println("Number of students: " + students.size());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论