2014-09-01 272 views
-5

我写了一个汽车程序,该程序有四种方法:加速,制动,齿轮和启动,并且我想确保在任何其他方法之前先调用启动方法三种方法被称为.pls我应该如何做到这一点。如何确保在java之前先调用某个方法

+0

你的程序将会有顺序,所以如果你先打电话或做一些if语句强迫它成为第一件事情会很好 – 2014-09-01 22:06:10

+0

'boolean running = false;'把它添加到你的班级。当启动被调用时,将其更改为true。如果调用其他方法,只有在运行== true时才运行它们。 – csmckelvey 2014-09-01 22:09:04

回答

5

我写了一个汽车程序,有四种方法加速,制动,齿轮和启动,并且我想确保在任何其他三种方法被调用之前先调用启动方法.pls我应该怎么做这个。

也许你应该考虑一种不同的方法。例如,我建议你实际上允许调用所有的方法,但是除非启动被调用,否则没有响应。例如,您可以给您的Car类设置一个布尔变量,称为running,在start()之前设置为true。那么如果运行是错误的,你的其他方法什么也不做

所以加速可能看起来像:

public void accelerate() { 
    if (!running) { 
    // exit the method and return to caller or throw exception 
    return; 
    } else { 
    // do what the method normally would do here 
    } 
} 
+1

感谢您认为我可以通过您的提示做些什么 – 2014-09-01 22:12:38

+0

另一种方法是'IllegalStateException'。 – chrylis 2014-09-01 22:56:39

8

这就是所谓的 “保持现状”。有这样做的方法很多,但也许是很基本的一个将保持boolean变量,它会告诉你,如果汽车启动与否:

public class Car { 
    private boolean isStarted = false; 
    public void start() { 
     ... // Do things 
     isStarted = true; 
    } 
    ... 
} 

现在你的其他方法需要检查isStarted,看看是否汽车处于适当的状态:

void accelerate() { 
    if (!isStarted) { 
     throw new IllegalStateException("Car must be started to accelerate"); 
    } 
    // Do other things 
} 
void brake() { 
    if (!isStarted) { 
     throw new IllegalStateException("Car must be started to brake"); 
    } 
    // Do other things 
} 
// ...and so on 
2

只需创建一个简单的标志让其他方法知道你的汽车已经启动。

喜欢的东西:

boolean started; 
start(){ started=true; } 

accelerate() { 
    if(started){ 
     // Your code here 
    } 
} 
1

你可以在技术上有一个类UnstartedCar他们的唯一方法是StartedCar start(),返回StartedCar与accelerate

这样的模式意味着编译器会拒绝接受任何不能正确操作汽车的文件,它会告诉用户在他们运行该程序之前他们不能加速未启动的汽车:

UnstartedCar unstartedCar = Dealer.buyCar(); 
unstartedCar.accelerate(); 

会导致:

error: cannot find symbol 
    unstartedCar.accelerate(); 
       ^
    symbol: method accelerate() 
    location: variable car of type UnstartedCar 

同时,

StartedCar startedCar = unstartedCar.start(); 
startedCar.accelerate(); 

会正常工作,因为这辆车是先启动的。这类似于一些汽车只是拒绝让你离开公园,除非你踩下刹车。它将永久消除由于在驾驶之前未启动汽车而产生的每一个可能出现的错误(让编译器捕获它被称为“类型安全”)。

但是,虽然这是一个非常有用的API功能,它可以防止大量的错误,并且在其他语言中受到高度追捧,但它不是惯用的Java而是

取而代之的是,如果您尝试在不启动的情况下进行加速(称为“快速失效”,并在dasblinkenlight的回答中进行了说明),则预计该车会发生爆炸。这种错误非常明显,易于早期修复,并且更符合常见的Java约定。

旧的方法是只是没有车做任何事情。这不再被推荐,因为错误很难找到。当客户抱怨他们的包裹没有交付时,您只能在数周后发现错误,并且发现车库里所有的司机都在加速器的地板上,但因为他们忘记首先启动车辆而没有移动。

相关问题