如何在Java中添加新记录?

huangapple go评论60阅读模式
英文:

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&lt;String&gt; students = new ArrayList&lt;&gt;();
System.out.print(&quot;Enter the new student name: &quot;);
String studentName = input.nextLine();
students.add(studentName);

System.out.println(&quot;Number of students: &quot; + students.size());

huangapple
  • 本文由 发表于 2020年7月25日 18:47:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/63087391.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定