Question

disclaimer

Hi, you could say this is a google-able question, but I've been looking around and all the examples I see are super specific to a certain problem, so I decided to just post my own question with my specific problem - some code here: http://pastebin.com/5ttK8Dry (I don't want it posted because I don't want someone googling my code, finding it online, and think that I copied it from somewhere because this site will show up... please leave it in the pastebin. If it somehow gets deleted, I will just post it again immediately). I hope you guys appreciate all my headers... :P Every time I use this site I get flak for having an unclear question, so I hope this one is very straightforward to follow!!

Explanation of current code

The code accepts a user-inputted wind speed. It uses a generic try-catch block to stop an input mismatch exception, and uses an if-statement to make sure the value entered is within the legal range. (See pastebin)

What I have to do

I now have an Environment class that has "wind speed" as a private attribute. In short, I need to create an object-oriented version of the code I have in the pastebin.

What I know

I have to code my own exceptions and encapsulate them, and then throw them when I'm setting the windpeed in my main class - if I supply a value that is illegal, the program should behave the same as it did before.

What I need help on

I don't really know where to start. In the code I have now, I see that I would need 2 exceptions - one for inputMismatch (which is already part of java), and one if I enter a value too high/low.

I know I have to code my own exception for the latter, but what about the former? That exception already exists...

The ultimate question

(a) How do I create my own exception to be thrown if the user enters a value too high/low? (b) How do I incorporate an exception that already exists into the process?

I can probably figure out the rest from there - I just need a place to get started.

Was it helpful?

Solution

try{
//get number

if(number<minRange || number>maxRange){
 throw new IllegalArgumentException();
}

//Rest of stuff


}catch(InputMismatchException e){
 System.out.println("Invalid input!");
 System.exit(-1);
}

OTHER TIPS

  public class Environment {
private double windspeed;

 public Environment(double speed) throws myException{
    if(speed<min || speed>max){
     throw new myException();
 }


 }


 class myException extends Exception{

 }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top