Im supposed to be giving the program two arguments: one for current speed in mph and the other, the speed limit in kph. My program must use the converter file to change your current speed to kph so as to be compared to the speed limit then warn the user via Dashboard display that they are speeding. But if only one arg is given, the program must use 40kph as the default speed limit. My problem lies in not knowing how to code an IF statement for a lack of args. Help!?!
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();
}
}
Just use:
SpeedLimit limit;
if (args.length < SOME_NUMBER) {
limit = 40;
}
*This is possible because args is just an Array of Strings - you can use the .length property on any Array object.
This should work.. Just set SpeedLimit to 40 by default and if 2 args were passed, update to the correct speed limit.
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]);
}
Here is a more complete example of how you could set this up.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With