【问题标题】:Incrementing ArrayElement Parameters based on previous ELEMENTS根据之前的 ELEMENTS 递增 ArrayElement 参数
【发布时间】:2019-06-13 20:50:39
【问题描述】:

我是 java 新手,但一直在玩数组列表,现在卡住了。

我从一个名为 Car 的类创建了一个数组列表,其中包含三个参数,其中一个称为 timesmoved

主类

public class GarageTester {

/**
 * @param args the command line arguments
 */
  public static void main(String[] args) throws IOException{
   // create Bank object
   Garage bashimGarage = new Garage() ;


  // create Scanner object associated with input file
  Scanner fileScan = new Scanner(new 
   File("C:\\Users\\jamison\\Desktop\\GarageData.txt")) ;

  // read BankAccount data from file, create objects, and add to list

   while ( fileScan.hasNextLine())      // while not eof
   {

     String fullText = fileScan.nextLine();
     // Split the acquired string into 2 based on the whitespace
     String[] splitText = fullText.split("\\s+");
     // String before whitespace split
     String licensePlate = splitText[0];
     // String after whitespace split
     String status = splitText[1];
     // create Car object
     Car newCar = new Car(licensePlate, status , 0) ;  
     // add to list   
     bashimGarage.addCar( newCar ) ;   

   }


  /*
    *Calculates the number of times car was temporary moved before departure
  */
  bashimGarage.carDepart();


  /*
    *Prints list of car license plates
    * Admits or declines a car to the garage
    * Prints if a car departs the Garage
    * When a car departs also prints the number of times it was moved
  */
   bashimGarage.moveCarInGarage();

汽车类

public class Car {

   private String licensePlate;    // License Plate Number
   private String status ;         // Status: Arivved or Departed
   private int moved;              /* How many times the car 
                                  got moved out of the garage
                                  */


public Car ( String licenseNum, String carStatus , int timesMoved)
 {   
    licensePlate = licenseNum ;
    status = carStatus ;
    moved = timesMoved;
 }


public String getLicenseNum()
{   
  return licensePlate;
}


public String getStatus()
{   
  return status;
}



 public int getTimesMoved()
{   
  return moved;
}



public int setTimesMoved(int times){
    moved = moved + times;
    return moved;
  }

}

车库类

public class Garage {
   private ArrayList<Car> list ;  // a list of BankAccount objects
   public int maxCars = 10;       // max number of cars allowed in garage
   public int currentCars = 0;    // current number of cars in garage


public Garage()
{
  list = new ArrayList<Car>() ;
}


 public void addCar(Car newCar)
 {
   list.add(newCar) ;        // calls "add" method of ArrayList class
 } 


  public void carDepart() {
    for (int i = 0; i < list.size(); i++) {
    Car current = list.get(i);   // get next car
    if (current.getStatus().equals("DEPART")) {
        int pos = list.indexOf(current);

        for (int j = 0; j < pos; j++) {
            list.get(j).setTimesMoved(1 + current.getTimesMoved());
        }

        list.remove(i);
        return;
     }

    }
 }



  public void moveCarInGarage()
  {
    for ( int i = 0 ; i < list.size() ; i++ )
    {
     Car current = list.get( i ) ;   // get next car
     if (current.getStatus().equals("ARRIVE"))
     {
         currentCars++; //Increments current # of cars in garage

       if (currentCars <= 10) // Checks if there is space in garage
       {
           //Prints license plate and arrival status to screen
           System.out.println("Car with license plate" + 
            current.getLicenseNum() + " has arrived "
                   + "and been moved into the garage");
       }
       else 
       {
           // Prints garage is full to screen
           System.out.println("The garage is full at this " +
           "time so come back later");
        }
     }
      else  
      {

         currentCars--; // Decrements current # of cars in garage
         /* 
         Prints license plate, departure status, 
         and number of times moved to screen
         */
         System.out.println("Car with license plate" + 
           current.getLicenseNum() + " is departing and has been moved " 
                 + current.getTimesMoved() + " times" );

       }
    }
 }

我正在读取应该像车库一样的文件的输入,并说明汽车是“到达”还是“出发”

我正在尝试使用 if 语句编写代码,如果状态为“Departing”,则当前元素将被删除,它前面的所有元素都会在其 “timesmoved parameter”中添加一个强>

我坚持的部分是,根据被删除的元素,数组列表中它前面的所有元素都将其 "timesmoved" 参数加一。

我想出了这个,但它似乎不起作用,因为当我调用第二种方法时,它总是说 0 表示移动的时间。

public void carDepart()
   {
     for ( int i = 0 ; i < list.size() ; i++ )
        {
         Car current = list.get( i ) ;   // get next car
            if (current.getStatus().equals("DEPART"))
            {
              int pos = list.indexOf(i);

                for ( int j = 0 ; pos < j ; j++)
                {
                 current.setTimesMoved(1 + current.getTimesMoved());
                }

                 list.remove(i);
                 return;
          }

       }  
    }

第二种方法

    public void moveCarInGarage()
    {
      for ( int i = 0 ; i < list.size() ; i++ )
    {
       Car current = list.get( i ) ;     // get next car
       if (current.getStatus().equals("ARRIVE"))
     {
         currentCars++;

       if (currentCars <= 10) 
       {
           System.out.println("Car with license plate" + 
            current.getLicenseNum() + " has been moved into the garage");
       }
       else 
       {
           System.out.println("The garage is full at this " +
           "time so come back later");
       }
   }
     else 
     {
         currentCars--;
         System.out.println("Car with license plate" + 
           current.getLicenseNum() + " is departing and has been moved " 
                 + current.getTimesMoved() + " times" );
     }
  }

}

【问题讨论】:

    标签: java for-loop if-statement arraylist


    【解决方案1】:

    第一种方法,第 8 行。 当您已经在i 中拥有pos 时,为什么还要尝试提取它。 int pos = list.indexOf(i); 将给出 -1。

    同样,在这个循环中

    for ( int j = 0 ; pos < j ; j++)
        {
              current.setTimesMoved(1 + current.getTimesMoved());
        }
    

    你总是指向数组列表中的同一个元素。

    相反,您可能希望对其进行如下编程:

    for ( int j = 0; j<i; j++)
        {
              Car car = list.get(j);
              car.setTimesMoved(1 + car.getTimesMoved());
        }
    

    【讨论】:

    • 我的逻辑是,当它第一次遇到状态为离开的元素时,它会获取其索引,然后扫描该索引之前的所有元素并将 timesMoved 递增 1。我不是 100% 确定你是什么意思是当你已经拥有它时提取帖子,因为我以前从未尝试过获取索引?对不起,如果我听起来有点迷茫
    • 哦。所以你想增加previoys汽车。我会修改的。
    • 通过提取我的意思是,由于您使用循环变量i 进行迭代,所以i 不会成为当前索引。您不需要显式提取当前索引的位置。
    • 我现在明白 Sand 提供了一个很好的例子,但即使使用编辑过的代码,由于某种原因它仍然给出 0
    【解决方案2】:

    您的方法存在以下问题,

    • 首先,您获取的是整数索引而不是对象。
    • 您的内部 for 循环条件错误。
    • 您总是递增当前对象的值,而不是 以前的。

    我已经用你的方法纠正了它们。使用以下一个,

    public void carDepart() {
            for (int i = 0; i < list.size(); i++) {
                Car current = list.get(i);   // get next car
                if (current.getStatus().equals("DEPART")) {
                    /* You can remove below line and replace pos with i in your inner loop. 
                    Since the current object position will be same as i */
                    int pos = list.indexOf(current);
    
                    for (int j = 0; j < pos; j++) {
                        list.get(j).setTimesMoved(1 + current.getTimesMoved());
                    }
    
                    list.remove(i);
                    return;
                }
    
            }
        }
    

    【讨论】:

    • 运行程序时,运行第二种方法后仍然显示移动了 0 次。让我编辑代码以包含更多信息
    • 我添加了更多代码,因为我仍然得到 0,我猜它现在可能是其他地方的错误
    • 添加了主要方法
    • 它工作正常。如果你用这个System.out.println("Car with license plate" + current.getLicenseNum() + " has moved " + current.getTimesMoved() + " times"); 替换moveCarInGarage 方法中的第一个打印,你应该会看到它的打印时间正确。也许您需要考虑一下您的条件?
    • 逻辑似乎在任何地方都是正确的,但它仍然总是说 0 知道为什么吗?另外,如果第一个语句是“ARRIVD”,而其他语句是离开,我为什么要替换第一个打印语句?
    猜你喜欢
    • 2016-06-27
    • 2021-12-02
    • 1970-01-01
    • 2019-09-22
    • 2016-03-29
    • 2018-10-11
    • 1970-01-01
    • 1970-01-01
    • 2018-08-06
    相关资源
    最近更新 更多