如何在Java中添加新记录?

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

How to add a new record in java?

问题

主程序:

  1. System.out.print("输入新学生姓名:");
  2. String studName = input.nextLine();
  3. newCourse.addStudent(studName);

类:

  1. public void addStudent(String studName){
  2. studentNames[noOfStudents] = studName;
  3. noOfStudents++;
  4. }

运行后显示如下错误:

  1. 异常信息:Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
英文:

Main program:

  1. System.out.print("Enter the new student name: ");
  2. String studName = input.nextLine();
  3. newCourse.addStudent(studName);

class:

  1. public void addStudent(String studName){
  2. studentNames[noOfStudents] = studName;
  3. noOfStudents++;
  4. }

After run it show me this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3

答案1

得分: 1

如果您想使用数组,由于它不可扩展,您需要创建一个比原数组多一个索引的基础副本,以将所需的元素放入其中。

以下示例使用自定义方法来实现:

  1. public static void main(String[] args) {
  2. final int[] start = {1, 7, -4},
  3. added = append(start, 77);
  4. System.out.println("added: " + Arrays.toString(added));
  5. }
  6. static public int[] append(final int[] values, final int newValue) {
  7. final int[] result = Arrays.copyOf(values, values.length + 1);
  8. result[values.length] = newValue;
  9. return result;
  10. }
英文:

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:

  1. public static void main(String[] args) {
  2. final int [] start = {1,7,-4},
  3. added = append(start, 77);
  4. System.out.println("added: " + Arrays.toString(added));
  5. }
  6. static public int[] append(final int[] values, final int newValue) {
  7. final int[] result = Arrays.copyOf(values, values.length + 1);
  8. result[values.length] = newValue;
  9. return result;}

答案2

得分: 0

使用数组进行诸如添加/移除之类的操作并不推荐。
开始使用列表将会让你的生活更加轻松。
以下是使用列表的示例:

  1. List<String> students = new ArrayList<>();
  2. System.out.print("输入新学生的姓名:");
  3. String studentName = input.nextLine();
  4. students.add(studentName);
  5. 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

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

确定