This is my game i created, i just need to add a try catch into it somehow and i am stuck.
/**
*
* #author
*/
import java.util.*;
public class magiceightball {
public static void main (String [] args){
questions();
}
public static void questions(){ //method
Scanner input = new Scanner(System.in);
while(true){
System.out.println();
System.out.println("Welcome to the Magic 8 Ball Game!");
System.out.println("Shake(Type 'Shake' to have you question answered, or type 'No more'to end the game");
String request = input.nextLine();
I think here is where i can add a try
if (request.equalsIgnoreCase("shake")){
answer();
}
else if(request.equalsIgnoreCase("No more")){
break;
}
else{
System.out.println("Invalid answer. Please try again!");
}
}
}
public static void answer(){
switch(shake()){
case 1:System.out.println("It is certain");
break;
case 2:System.out.println("It is decidedly so");
break;
case 3:System.out.println("Most likely");
break;
case 4:System.out.println("Ask again later");
break;
case 5:System.out.println(" Better not tell you now");
break;
case 6:System.out.println("Don't count on it");
break;
case 7:System.out.println("My reply is no");
break;
case 8:System.out.println("My sources say no");
break;
case 9:System.out.println("Unlikely");
break;
case 10:System.out.println("Doubtful");
break;
}
}
public static int shake(){
This is another area i think could use a try and catch to check for arithmetic
Random rand = new Random();//using random numbers
int randomInt = rand.nextInt(10 - 1 + 1) + 1;//i used this to get a random number from 1-10
System.out.println(randomInt);
return randomInt;
}
}
Since exceptions are intended primarily for handling errors or other exceptional/unexpected events, a good candidate for such would be your answer() method. Imagine what could go wrong that you might not expect.
For example, what happens when your shake() method returns a value that cannot be handled by your switch statement? Consider a situation in which you increased the range of your random number generator and forgot to add additional cases; or, you didn't dynamically load enough answers from a configuration file.
A simple solution may be to add a default: case that returns some "catch-all" answer (e.g. "I don't know"). However, a better solution would be having the default: case throw an Exception to indicate that your method does not have answers for some rolls.
int roll = shake();
switch ( roll ) {
...
default:
throw new Exception( "No answer for roll: " + roll );
}
Related
In the clean code book is an example about using exceptions rather than return codes:
You either set an error flag or returned an error code.
public class DeviceController {
...
public void sendShutDown() {
DeviceHandle handle = getHandle(DEV1);
// Check the state of the device
if (handle != DeviceHandle.INVALID) {
// Save the device status to the record field
retrieveDeviceRecord(handle);
// If not suspended, shut down
if (record.getStatus() != DEVICE_SUSPENDED) {
pauseDevice(handle);
clearDeviceWorkQueue(handle);
closeDevice(handle);
} else {
logger.log("Device suspended. Unable to shut down");
}
} else {
logger.log("Invalid handle for: " + DEV1.toString());
}
}
...
}
Unfortunately, it's easy to forget. For this reason, it is better to throw an exception when you encounter an error. The calling code is cleaner. Its logic is not obscured by error handling.
public class DeviceController {
...
public void sendShutDown() {
try {
tryToShutDown();
} catch (DeviceShutDownError e) {
logger.log(e);
}
}
private void tryToShutDown() throws DeviceShutDownError {
DeviceHandle handle = getHandle(DEV1);
DeviceRecord record = retrieveDeviceRecord(handle);
pauseDevice(handle);
clearDeviceWorkQueue(handle);
closeDevice(handle);
}
private DeviceHandle getHandle(DeviceID id) {
...
throw new DeviceShutDownError("Invalid handle for: " + id.toString());
...
}
...
}
The code is better because two concerns that were tangled, the algorithm for device shutdown and error handling, are now separated. You can look at each of those concerns and understand them independently.
Now my question is not so much about the whether to use exceptions or return codes but I am wondering about the unused DeviceRecord in the second "good example", which uses exceptions.
Wouldn't it be enough to just call retrieveDeviceRecord(handle); to save the device status to the record field as in the "bad example code" but change the method to also throw an exception in case anything goes wrong during retrieveDeviceRecord(handle);? Or is there a purpose of returning DeviceRecord but not using it?
I am trying to write test case but stuck with this error. How to fix this error ?
#Override
public boolean isDuplicateSystemDetail(SystemFormBean systemFormBean){
List<BrmSystem> list = systemDao.isDuplicateSystemDetail(systemFormBean);
if(CollectionUtils.isNotEmpty(list)){
return true;
}else{
return false;
}
}
---------------------------------------------------------------------------
#Test
public void isDuplicateSystemDetail_Should_Return_True(){
List<BrmSystem> list = new ArrayList<BrmSystem>();
BrmSystem brmSystem = new BrmSystem();
SystemFormBean systemFormBean = new SystemFormBean();
brmSystem.setSystemName("Test");
list.add(brmSystem);
when(systemDao.isDuplicateSystemDetail(systemFormBean)).thenReturn(list);
}
Probably SystemFormBean class doesn't override equals(). So when isDuplicateSystemDetail(systemFormBean) invokes, it has another object of this class as a parameter which is not the same as the one you've created manually (by default Object.equals() compares memory adresses which would be false in your case).
Try to override equals() to compare by f.e. actual fields of SystemFormBean or rewrite "when" clause as
systemDao.isDuplicateSystemDetail(Mockito.any(SystemFormBean.class))
I'm developing a project using Graphhopper core to calculate optimal routes. I incorporated some real traffic data by modifying speed assigned to edges and calculated optimal routes in two ways: the "default" way and the way, which considers traffic.
Now, I try to compare those routes and investigate how travel time changes. What I would like to do is to calculate travel time on the optimal route, which was found using default speed assigned to edges, but travel time should be calculated using custom speed values (those, which take into account real traffic). In other words, is it possible to use Graphhopper to calculate travel time on a specific route (not optimal one)?
A solution, which came to my mind, is to implement custom FlagEncoder (as described here), extend Path class and use them to calculate travel time using speed values, which considers traffic. However, maybe you, guys, know simpler way to achieve this.
I finally managed to solve the problem so I share my solution.
To store custom speed as an extra value I extended class CarFlagEncoder.
public class CustomCarFlagEncoder extends CarFlagEncoder {
public static final int CUSTOM_SPEED_KEY = 12345;
private EncodedDoubleValue customSpeedEncoder;
public CustomCarFlagEncoder() {
super();
}
public CustomCarFlagEncoder(PMap properties) {
super(properties);
}
public CustomCarFlagEncoder(String propertiesStr) {
super(propertiesStr);
}
public CustomCarFlagEncoder(int speedBits, double speedFactor, int maxTurnCosts) {
super(speedBits, speedFactor, maxTurnCosts);
}
#Override
public int defineWayBits(int index, int shift) {
shift = super.defineWayBits(index, shift);
customSpeedEncoder = new EncodedDoubleValue("Custom speed", shift, speedBits, speedFactor,
defaultSpeedMap.get("secondary"), maxPossibleSpeed);
shift += customSpeedEncoder.getBits();
return shift;
}
#Override
public double getDouble(long flags, int key) {
switch (key) {
case CUSTOM_SPEED_KEY:
return customSpeedEncoder.getDoubleValue(flags);
default:
return super.getDouble(flags, key);
}
}
#Override
public long setDouble(long flags, int key, double value) {
switch (key) {
case CUSTOM_SPEED_KEY:
if (value < 0 || Double.isNaN(value))
throw new IllegalArgumentException("Speed cannot be negative or NaN: " + value
+ ", flags:" + BitUtil.LITTLE.toBitString(flags));
if (value > getMaxSpeed())
value = getMaxSpeed();
return customSpeedEncoder.setDoubleValue(flags, value);
default:
return super.setDouble(flags, key, value);
}
}
#Override
public String toString() {
return CustomEncodingManager.CUSTOM_CAR;
}
}
In order to be able to use custom FlagEncoder, I created CustomEncodingManager, which extends EncodingManager and handles CustomCarFlagEncoder.
public class CustomEncodingManager extends EncodingManager {
public static final String CUSTOM_CAR = "custom_car";
public CustomEncodingManager(String flagEncodersStr) {
this(flagEncodersStr, 4);
}
public CustomEncodingManager(String flagEncodersStr, int bytesForFlags )
{
this(parseEncoderString(flagEncodersStr), bytesForFlags);
}
public CustomEncodingManager(FlagEncoder... flagEncoders) {
super(flagEncoders);
}
public CustomEncodingManager(List<? extends FlagEncoder> flagEncoders) {
super(flagEncoders);
}
public CustomEncodingManager(List<? extends FlagEncoder> flagEncoders, int bytesForEdgeFlags) {
super(flagEncoders, bytesForEdgeFlags);
}
static List<FlagEncoder> parseEncoderString(String encoderList )
{
if (encoderList.contains(":"))
throw new IllegalArgumentException("EncodingManager does no longer use reflection instantiate encoders directly.");
String[] entries = encoderList.split(",");
List<FlagEncoder> resultEncoders = new ArrayList<FlagEncoder>();
for (String entry : entries)
{
entry = entry.trim().toLowerCase();
if (entry.isEmpty())
continue;
String entryVal = "";
if (entry.contains("|"))
{
entryVal = entry;
entry = entry.split("\\|")[0];
}
PMap configuration = new PMap(entryVal);
AbstractFlagEncoder fe;
if (entry.equals(CAR))
fe = new CarFlagEncoder(configuration);
else if (entry.equals(BIKE))
fe = new BikeFlagEncoder(configuration);
else if (entry.equals(BIKE2))
fe = new Bike2WeightFlagEncoder(configuration);
else if (entry.equals(RACINGBIKE))
fe = new RacingBikeFlagEncoder(configuration);
else if (entry.equals(MOUNTAINBIKE))
fe = new MountainBikeFlagEncoder(configuration);
else if (entry.equals(FOOT))
fe = new FootFlagEncoder(configuration);
else if (entry.equals(MOTORCYCLE))
fe = new MotorcycleFlagEncoder(configuration);
else if (entry.equals(CUSTOM_CAR)) {
fe = new CustomCarFlagEncoder(configuration);
}
else
throw new IllegalArgumentException("entry in encoder list not supported " + entry);
if (configuration.has("version"))
{
if (fe.getVersion() != configuration.getInt("version", -1))
{
throw new IllegalArgumentException("Encoder " + entry + " was used in version "
+ configuration.getLong("version", -1) + ", but current version is " + fe.getVersion());
}
}
resultEncoders.add(fe);
}
return resultEncoders;
}
}
Then, I set the custom EncodingManager to GraphHopper object hopper.setEncodingManager(new CustomEncodingManager(CustomEncodingManager.CUSTOM_CAR));
I assign custom speed to an edge as an extra value edge.setFlags(customCarEncoder.setDouble(existingFlags, CustomCarFlagEncoder.CUSTOM_SPEED_KEY,
newSpeed));
Finally, to use custom speed while calculating travel time, I slightly modified method clacMillis form class Path from package com.graphhoper.routing.
protected long calcMillis( double distance, long flags, boolean revert )
{
if (revert && !encoder.isBackward(flags)
|| !revert && !encoder.isForward(flags))
throw new IllegalStateException("Calculating time should not require to read speed from edge in wrong direction. "
+ "Reverse:" + revert + ", fwd:" + encoder.isForward(flags) + ", bwd:" + encoder.isBackward(flags));
double speed = revert ? encoder.getReverseSpeed(flags) : encoder.getSpeed(flags);
double customSpeed = encoder.getDouble(flags, 12345);
if (customSpeed > 0) {
speed = customSpeed;
}
if (Double.isInfinite(speed) || Double.isNaN(speed) || speed < 0)
throw new IllegalStateException("Invalid speed stored in edge! " + speed);
if (speed == 0)
throw new IllegalStateException("Speed cannot be 0 for unblocked edge, use access properties to mark edge blocked! Should only occur for shortest path calculation. See #242.");
return (long) (distance * 3600 / speed);
}
I want to register a generic delegate that resolves itself at runtime, but I cannot find a way to do this on generics.
Given a delegate that looks like this:
public delegate TOutput Pipe<in TInput, out TOutput>(TInput input);
And given a discretely registered delegate that look like this:
public class AnonymousPipe<TInput, TOutput>
{
public Pipe<TInput, TOutput> GetPipe(IContext context)
{...}
I want to register a function along the lines of this:
builder.RegisterGeneric(typeof(Pipe<,>)).As(ctx =>
{
var typeArray = ctx.RequestedType.GetGenericArguments();
// this can be memoized
var pipeDefinition = ctx.Resolve(typeof(AnonymousPipe<,>).MakeGenericType(typeArray));
return pipeDefinition.GetPipe(ctx);
I cannot find a way to provide an implementation of the generic as a parameter in Autofac - I may just be missing something. I know I can do this through a generic object or interface, but I want to stick with the lightness of a delegate. It makes unit testing super simple on the injection of these.
Any thoughts? I am having to do discrete registrations at the moment(one per type combination and no generics).
I can only come up with the registration source solution (the universal hammer in Autofac.)
class PipeSource : IRegistrationSource
{
public bool IsAdapterForIndividualComponents { get { return true; } }
public IEnumerable<IComponentRegistration> RegistrationsFor(
Service service,
Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor)
{
var swt = service as IServiceWithType;
if (swt == null || !swt.ServiceType.IsGenericType)
yield break;
var def = swt.ServiceType.GetGenericTypeDefinition();
if (def != typeof(Pipe<,>))
yield break;
var anonPipeService = swt.ChangeType(
typeof(AnonymousPipe<,>).MakeGenericType(
swt.ServiceType.GetGenericArguments()));
var getPipeMethod = anonPipeService.ServiceType.GetMethod("GetPipe");
foreach (var anonPipeReg in registrationAccessor(anonPipeService))
{
yield return RegistrationBuilder.ForDelegate((c, p) => {
var anon = c.ResolveComponent(anonPipeReg, p);
return getPipeMethod.Invoke(anon, null); })
.As(service)
.Targeting(anonPipeReg)
.CreateRegistration();
}
}
}
Then:
builder.RegisterSource(new PipeSource());
Now, I'm certain that I can't type that code into a web page and have it actually compile and run, but it might come close :)
I have a static Settings class where my application can retrieve settings from. The problem is that some of these settings are strings, while others are ints or numbers. Example:
package
{
public final class Settings
{
public static function retrieve(msg:String)
{
switch (msg)
{
case "register_link":
return "http://test.com/client/register.php";
break;
case "time_limit":
return 50;
break;
}
}
}
}
Now, in the first case it should send a string and in the second a uint. However, how do I set this in the function declarement? Instead of eg. function retrieve(msg:String):String or ...:uint? If I don't set any data type, I get a warning.
HanClinto has answered your question, but I would like to also just make a note of another possible solution that keeps the return types, typed. I also find it to be a cleaner solution.
Rather than a static retrieve function, you could just use static consts, such as:
package
{
public final class Settings
{
public static const REGISTER_LINK:String = "my link";
public static const TIME_LIMIT:uint= 50;
}
}
And so forth. It's personal preference, but I thought I would throw it out there.
Use *
public static function retrieve(msg:String):*
{
if (msg == "age") {
return 23;
} else {
return "hi!";
}
}