【问题标题】:Array used to create objects with incrementing name用于创建名称递增的对象的数组
【发布时间】:2015-10-13 11:47:21
【问题描述】:

所以我希望 sArr 在 if 之后有一个数字,并且每次循环通过时都会增加它。我不知道我做错了什么,有人可以解释吗?

import java.util.*;
public class StudentTest {


  public static void main(String[] args){
  Scanner in = new Scanner(System.in);
  String id, name, gender, address;
  Student[] sArr = new Student[4];
  int age;
    for(int i=0; i>=sArr.length(); i++){
      System.out.println("student id.");
      id = in.nextLine();
      in.nextLine();
      System.out.println("Sutdent name.");
      name = in.nextLine();
      in.nextLine();
      System.out.println("Gender.");
      gender = in.nextLine();
      in.nextLine();
      System.out.println("Address.");
      address = in.nextLine();
      in.nextLine();
      System.out.println("Age");
      age = in.nextInt();

      Student sArr[i] = new Student(id, name, gender, age, address);
      s2.display();
    }
  }
}

这段代码给了我这些错误:

--------------------Configuration: <Default>--------------------
C:\StudentTest.java:31: error: ']' expected
        Student sArr[i] = new Student(id, name, gender, age, address);
                     ^
C:\Users\Bart\Desktop\Bart Kosinski_2886295_Assignment01\StudentTest.java:31: error: illegal start of expression
        Student sArr[i] = new Student(id, name, gender, age, address);
                      ^
2 errors

Process completed.

【问题讨论】:

    标签: java arrays object increment


    【解决方案1】:

    改变

    Student sArr[i] = new Student(id, name, gender, age, address);
    

    sArr[i] = new Student(id, name, gender, age, address);
    

    Student sArr[i] 是一个(无效的)数组声明。您之前已经声明了数组(在Student[] sArr = ... 中)。现在您想将 Student 引用分配给数组的索引。

    这将解决编译错误。您应该修复的另一件事是循环的条件。

    for(int i=0; i>=sArr.length(); i++)
    

    应该是

    for(int i=0; i<sArr.length(); i++)
    

    否则循环将永远不会被执行。

    【讨论】:

      猜你喜欢
      • 2016-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-06
      • 1970-01-01
      • 2013-04-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多