将整数转换为类型Java的数组



我接收一个具有名称(表)的文件和座位数:

table1 6

table2 2

table3 4

我有一系列的课堂预订,可以占用名称和座位。我很难将座位数转换为阵列。我该怎么做?

公共类保留{

protected String id;
private Reservation[] arrayRes = new Reservation[10];

public Reservable (Scanner fileIn) {
    while(fileIn.hasNext()) {
        id = fileIn.next();
        for(int i = 0; i < arrayRes.length; i++) {
            int seat = fileIn.nextInt();
            arrayRes[i] = seat;
        }
    }

}

这是我的预订课:

public class Reservation {
    private String name;
    private int timeSlot;
    private Reservable myReservable;
    public Reservation(String name, int timeSlot) {
        this.name = name;
        this.timeSlot = timeSlot;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getTimeSlot() {
        return timeSlot;
    }
    public void setTimeSlot(int timeSlot) {
        this.timeSlot = timeSlot;
    }
    public Reservable getMyReservable() {
        return myReservable;
    }
    public void setMyReservable(Reservable myReservable) {
        this.myReservable = myReservable;
    }
    public boolean isActive() {
        return false;
    }

您可以按行读取行,因为您的文件具有按线预订。我建议您拥有一个带有两个参数(名称和NBSEAT)的预订构造函数。
备注:您的预订阵列的大小固定:10。如果您的文件具有10个以上的元素,则ArrayIndexOutOfBoundsException将被升起。
如果预订数可能优于10或可变,则应使用列表而不是数组。

protected String id;
private Reservation[] arrayRes = new Reservation[10];

public Reservable (Scanner fileIn) {
    int i=0;
    while(fileIn.hasNextLine()) {
        String line = fileIn.nextLine();
        String[] token = line.split("\s");
        String name = token[0];
        int nbSeat= Integer.valueOf(token[1)];
         // add in your array
         Reservation reservation = new Reservation(name,nbSeat);
        arrayRes[i] = reservation ;
    }
      i++;
}

和预订:

public class Reservation{
  public Reservation(String name, int nbSeat){
    this.name=name;
    this.nbSeat=nbSeat;
  }
 }

您需要向我们展示您的预订类的外观,但是如果它使用常规的Geters和Setters,这是正确的方法:

public Reservable (Scanner fileIn) {
    while(fileIn.hasNext()) {
        for(int i = 0; i < arrayRes.length; i++) {
            int seat = fileIn.nextInt();
            arrayRes[i].setSeat(seat);
            id = fileIn.next();
            arrayRes[i].setId(id);
            }
        }
}

相关内容

  • 没有找到相关文章

最新更新