对不起,如果这是一个令人困惑的问题或重复。所以我有一个名为“Driveable”的布尔方法,当这是真的时,我想打印出汽车行驶的速度。然后我还想展示这辆车是什么档位。但是,我想传递int“speed”并在调用该方法时输入参数。但是,当我在“gearChange”方法中调用此方法时,它要求我输入一个整数,我不想输入不过,我想传递我已经在“速度”方法中输入的参数。那么在另一个方法中再次调用该方法时是否可以传递参数或返回值?再次为这个令人困惑的问题感到抱歉。我意识到可能有其他方法可以得到我的答案,但为了将来参考,我想知道这样的事情是否可能。所以我'
public static int speed(int speed){
if(driveable()){
System.out.print(" you are going " + speed + " miles per hour");
return speed;
}else{
System.out.print("The car is not drive able");
return -1;
}
}
public static void gearChange(){
//here:
if(speed(speed) >= 1 && speed(speed) <= 20){
System.out.print("You are in first gear");
etc...
}
speed(int 15);
gearChange();
欢迎来到 SO。
是的,您可以在方法之外设置变量。注意:这不是很容易理解的代码,但我包含它是为了演示如何在方法之外设置变量。我还稍微更新了命名以区分变量。
private int currentSpeed;
public static boolean driveable() {
return true; //or whatever your logic may be
}
public int testSpeed(int speed) {
if (driveable()) {
System.out.print(" you are going " + speed + " miles per hour");
this.currentSpeed = speed;
return speed;
}
else {
System.out.print("The car is not driveable");
this.currentSpeed = speed;
return -1;
}
}
public void gearChange() {
if (testSpeed(this.currentSpeed) >= 1 && testSpeed(this.currentSpeed) <= 20) {
System.out.print("You are in first gear");
}
}
@Test //run in Junit to see the output
public void testIt() {
testSpeed(15);
gearChange();
}
在许多情况下,您会使用 getter 和 setter 方法(getX()
并setX()
访问值(除非您正在进行一些函数式编程)。
请注意,您还会testSpeed()
多次调用该方法。
你会想要重新审视这个设计,并明确你想要实现的目标。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句