Home > Software engineering >  I just need one line for the output "the car has 6 doors"(the one with more doors).But the
I just need one line for the output "the car has 6 doors"(the one with more doors).But the

Time:07-12

package Car;

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Car myCar = new Car();
        myCar.AddDoor();
        myCar.AddDoor();
    }

}

class Car {
    public int door = 4;
    
    public void AddDoor() {
        this.door  ;
        System.out.println("The car has   "   door   " "   "doors");
    }
}

CodePudding user response:

Your requirement is to add doors without printing anything about the doors. The code you posted is doing both in one method: this.door as well as System.out.println(). Instead, you need two different methods. Here's a way to edit what you posted to work like you want.

  1. Remove the System.out.println() from addDoor() (notice the lowercase first letter, that follows Java naming conventions). As you noted, you want to add a door without printing anything about the door totals. That would leave your method looking like this:

    public void addDoor() {
        this.door  ;
    }
    
  2. Make a new method in your Car class, call it printDoorInfo() or some such, and move your println() code there, like this:

    public void printDoorInfo() {
        System.out.println("The car has "   this.door   " doors");
    }
    
  3. In your calling code, after you have called myCar.addDoor() as many times as you like, call your new door info printer:

    myCar.printDoorInfo();
    
  • Related