public class DetailedSpeedSetter
{
public static void main(String args[])
{
double kph;
double mph;
double SpeedLimit;
mph = Text.toNonnegativeDouble(args [0]);
kph = Converter.toKPH(mph);
SpeedLimit = Text.toNonnegativeDouble(args[1]);
/**
* Determines whether the given speed exceeds the given limit
*
* @param speed The speed in km/hr
* @param limit The speed limit in km/hr
* @return true if speed exceeds limit and false otherwise
*/
public static boolean isSpeeding(double speed, double limit)
{
speed = kph;
limit = SpeedLimit;
if (speed > limit);
return true;
if (speed <= limit);
return false;
}
Dashboard.setSpeed(kph);
Dashboard.setSpeeding();
}
}
答案 0 :(得分:7)
只需使用:
SpeedLimit limit;
if (args.length < SOME_NUMBER) {
limit = 40;
}
*这是可能的,因为args只是一个字符串数组 - 您可以在任何Array对象上使用.length属性。
答案 1 :(得分:4)
这应该可行..默认情况下将SpeedLimit设置为40,如果传递了2个args,请更新到正确的速度限制。
double SpeedLimit = 40;
double mph = Text.toNonnegativeDouble(args[0]);
double kph = Converter.toKPH(mph);
if (args.length == 2)
{
// You have two args
SpeedLimit = Text.toNonnegativeDouble(args[1]);
}
以下是一个更完整的示例,说明如何设置它。
public class DetailedSpeedSetter
{
public static void main(String args[])
{
double mph = Text.toNonnegativeDouble(args [0]);
double kph = Converter.toKPH(mph);;
double SpeedLimit = 40;
if (args.length == 2)
{
SpeedLimit = Text.toNonnegativeDouble(args[1]);
}
Dashboard.setSpeed(speed);
if (isSpeeding(kph, SpeedLimit))
{
Dashboard.setSpeeding(true);
}
else
{
Dashboard.setSpeeding(false);
}
}
/**
* Determines whether the given speed exceeds the given limit
*
* @param speed The speed in km/hr
* @param limit The speed limit in km/hr
* @return true if speed exceeds limit and false otherwise
*/
public static Boolean isSpeeding(double speed, double limit)
{
if (speed > limit)
{
return true;
}
return false;
}
}
答案 2 :(得分:1)
与您的问题有关。请注意您的代码存在严重缺陷:您不应在;
之后使用if
这样的用户:
if (speed > limit);
return true;
由于没有大括号,它将运行空语句,即使speed <= limit
,它也会在单个时间内返回true。从ifs中删除;
:
if (speed > limit)
return true;
答案 3 :(得分:0)
简单的1行选项是第三级运算符:
limit = args.length == 2 ? args[1] : 40;