Here's the problem to solve: a method of a class that represents a gas network. This class manages objects of type Line that represent each single gas supply line.
An object of type Line is represented by the following members:
String startCity;
String endCity;
int capacityUsed;
int capacityAvail;
int maxCapacity;
The method I'm having trouble implementing is:
boolean carry(String city1, String city2, int capacity)
Consider all the lines from city1 tocity2. For each of these lines
try using capacity with the method use() (I don't think it's necessary to know how
use() works ). If use() throws the exception CapacitaSuperataException search
other lines between city1 and city2, if there are no other lines use()
must return False. If a call to use() does not throw CapacitaSuperataException means that the line was assigned the capacity, and the method returns True.
I tried some solutions but I don't know how to manage exceptions.
Thanks
Try using the try-catch inside a loop covering all suitable lines in your carry-Method:
for (Line line : getLines("start", "end"))
{
try
{
line.use(cap);
System.out.println("Line used, great!");
return true;
}
catch (CapacitaSuperataException e)
{
System.out.println("Line full, try next");
}
}
System.out.println("No line found");
return false;
public void use(int desiredCapacity) throws CapacitaSuperataException {
if(desiredCapacity > maxCapacity) throw CapacitaSuperataException
...
}
public void example() {
try {
this.use(999999)
} catch(CapacitaSuperataException) { /* show error message */ }
}
Related
I'm attempting to run a function concurrently using QtConcurrent but I'm running into issues with one of the arguments.
As a precursor, lets say I have the following classes and "interfaces":
class DataMessage : public QObject {
Q_OBJECT
// ... fields and methods
};
class ITimeStampInfo {
public:
virtual QDateTime timestamp() const = 0;
};
Q_DECLARE_INTERFACE(ITimeStampInfo, "My.TimeStampInfo/1.0")
class IDataLengthInfo {
public:
virtual int dataLength() const = 0;
};
Q_DECLARE_INTERFACE(IDataLengthInfo, "My.IDataLengthInfo/1.0")
class DataMessage1 : public DataMessage, public ITimeStampInfo {
Q_OBJECT
Q_INTERFACES(ITimeStampInfo)
// other fields, etc
QDateTime timestamp() const;
};
class DataMessage2 : public DataMessage, public IDataLengthInfo {
Q_OBJECT
Q_INTERFACES(IDataLengthInfo)
// other fields
int dataLength() const;
};
And a class function called processDataMessages:
void MyClass::processDataMessages(DataMessage *msg) {
// Previous to this function being called, concrete `DataMessage`
// instances are created and passed by pointer into this function
// Determine the data in the message
IDataLengthInfo *dl = qobject_cast<IDataLengthInfo*>(msg);
if (dl) {
qDebug() << "Got a message with IDataLengthInfo";
}
ITimeStampInfo *ts = qobject_cast<ITimeStampInfo*>(msg);
if (ts) {
qDebug() << "Got a message with ITimeStampInfo";
}
// etc
}
This processDataMessages is called in a slot. During normal operation, this function works perfectly and the qDebug() statements execute as expected as the pointer is correct - for example, inspecting the pointer type in the debugger results in a DataMessage1 type, for instance
I now want to run this function asynchronously as potentially, there may be a bit of work to do. If I try to execute this function using QtConcurrent::run from within the slot as follows:
void MyClass::dataReceived(DataMessage *msg) {
// this->processDataMessages(msg);
QtConcurrent::run(this, &MyClass::processDataMessages, msg);
}
Now when I break on the first qobject_cast line in the processDataMessages function, I can see that the msg pointer is of type DataMessage and not any of the DataMessage1 or DataMessage2 types.
Something is being lost during the operation of QtConcurrent::run and its probably something dumb I've missed.
Ok, so as it turns out, the following code works:
QFuture<void> f = QtConcurrent::run(this, &MyClass::processDataMessages, msg);
// Wait for the function to finish
f.waitForFinished();
Doesn't really seem any different to the original but something in the return value may be maintaining state??
I can't seem to make this work let alone compile and I am at loss at how to fix it. My teacher gave us the following code (simplified for question's sake):
public static void doing1(String s) {
// add code here
}
public static void doing2(char start, char end) {
// add code here
}
public static int doing3(int num) {
// add code here
}
public static void doing4(Scanner keyboard) {
// add code here
}
I know what needs to go in each method (the work I mean) I just don't know how to print it out in the main method. We cannot change the code given to us, only add to it.
Thank you!
Overloading a method means having the same method name but the method signature (the parameters passed in) is different. So, what you have isn't actually an overload, it is for unique methods because they all have different names. As far as not compiling... what you posted looks fine - perhaps you have an error above or below that code. I believe this is what you are looking for:
public static void doing(String s) {
// add code here
}
public static void doing(char start, char end) {
// add code here
}
public static int doing(int num) {
// add code here
}
public static void doing(Scanner keyboard) {
// add code here
}
Here's a reference on overloads from the almighty John Skeet
In the following code userexception class defined below is inheriting ApplicationException class. To my knowledge I know base keyword is used to pass the parameter, to parent class constructor. Here ApplicationException is the parent class. If this is the case, I wonder how does the object e of userexception class in the catch block can act as an argument and store the information "Transaction was unuccessful" , though Amount_To_WithDraw is not the parent class for userexception class. I want to know the in and out mechanism happening here when an exception is caught.
class Program
{
static void Main(string[] args)
{
Amount_To_WithDraw A = new Amount_To_WithDraw();
Console.WriteLine("Enter the amount to withdraw");
int cash = Convert.ToInt32(Console.ReadLine());
A.CheckBalance(cash);
Console.Read();
}
}
class userexception : ApplicationException
{
public userexception(string Message)
: base("Transaction was unsuccessful") -> for which class base
refers to here.
{
Console.WriteLine(Message);
}
}
class Amount_To_WithDraw
{
public void CheckBalance(int Amount)
{
int Balance = 1000;
try
{
if ((Balance - Amount) < 500 && (Balance - Amount) > 0)
{
throw new userexception("Least Balance");
}
else if ((Balance - Amount) < 0)
{
throw new userexception("Transaction Leads To Negative Balance");
}
else
Console.WriteLine("Transaction Success");
}
catch (userexception e) -> how can the object e of userexception class
can be considered as an argument for the
parameter sent using base key word
above.
{
Console.WriteLine(e.Message);
}
}
}
Ignore exceptions here. All you're seeing is the equivalent of this:
public class Parent
{
private readonly string message;
public string Message { get { return message; } }
public Parent(string message)
{
this.message = message;
}
}
public class Child : Parent
{
// Just pass the message parameter up to the parent
public Child(string message) : base(message) {}
}
Parent x = new Child("foo");
Console.WriteLine(x.Message);
It's exactly the same. In your case, you're using the Exception.Message property, which is populated by the message passed up the constructor chain.
It's unfortunate that you've called the parameter Message in the userexception constructor - partly because it's unconventional (it should start with m; your type name ignores naming conventions too), partly because you're not passing it up as the exception message, and partly because it has the same name as the property that you're later fetching.
You might find the whole thing more understandable if you change that constructor to:
public userexception(string message)
: base("Transaction was unsuccessful: " + message)
{
}
Then you'd end up with your caught exception having a Message property value of:
Transaction was unsuccessful: Least Balance
(or whatever).
I am relatively new to C#, maybe you could help me with this.
I got a couple of methods callServiceXY(param1, param2, ...) that call a certain service. For many reasons these service calls can go wrong (and I don't really care for the reason in the end). So basically I need to always wrap them with something like this - to have them execute again if something goes wrong:
var i = 3;
while(i>0)
try{
call...()
} catch{
i--;
}
i=0;
}
I'd rather write this code only once. Could I somehow have a method like tryXtimes(int x, callService()) that allows me to execute an undefined or anonymous method? (I have Javascript in mind where this is possible...)?
Yes this is possible. C# 3.5 added support for Action and Func<T> types. An Action won't return any value, a Func will always return a value.
You have several different versions that also accept a number of parameters. The following Console Applications describes how you could do this:
using System;
namespace Stackoverflow
{
class Service
{
public int MyMethod() { return 42; }
public void MyMethod(string param1, bool param2) { }
public int MyMethod(object paramY) { return 42; }
}
class Program
{
static void ExecuteWithRetry(Action action)
{
try
{
action();
}
catch
{
action();
}
}
static T ExecuteWithRetry<T>(Func<T> function)
{
try
{
return function();
}
catch
{
return function();
}
}
static void Main(string[] args)
{
Service s = new Service();
ExecuteWithRetry(() => s.MyMethod("a", true));
int a = ExecuteWithRetry(() => s.MyMethod(1));
int b = ExecuteWithRetry(() => s.MyMethod(true));
}
}
}
As you can see, there are two overloads for ExecuteWithRetry. One returning void, one returning a type. You can call ExecuteWithRetry by passing an Action or a Func.
--> Edit: Awesome! Just a little extra code to complete the example:
With anonymous function/method:
ExecuteWithRetry(() =>
{
logger.Debug("test");
});
And with more parameters (action, int)
Method header:
public static void ExecuteWithRetryX(Action a, int x)
Method call:
ExecuteWithRetryX(() => { logger.Debug("test"); }, 2);
I would use the strategy/factory pattern(s) for this. This answer https://stackoverflow.com/a/13641801/626442 gives and example of the use of the strategy/factory pattern with links. The question at the above link will give you another type of example where this pattern can be adopted.
There are great examples of these design patterns here and the following are detailed intros to the Strategy pattern and the Factory pattern. The former of the last two links also shows you how to combine the two to do something like what you require.
I hope this helps.
Try following
void CallServiceXY(params object []objects)
{
Console.WriteLine("a");
throw new Exception("");
}
void Retry(int maxRetryCount, Action<object[]> action, params object[] obj)
{
int retryCount = 1;
while ( retryCount <= maxRetryCount)
{
try
{
action(obj);
return;
}
catch
{
retryCount++;
}
}
}
void Main()
{
Retry(2,CallServiceXY);
Retry(2,CallServiceXY,"");
Retry(2,CallServiceXY,"","");
}
Demo here
Trick is Action<object[]> that accepts object array and return void and params keyword in Retry method.
To return non void value, Change Action<object[]> to Func<T, object[]>.
I've seen some developers use the out keyword on parameter lists of void functions. I'm quite unclear on what the pros and cons are of code below:
List<string> listOfResult;
public void public void (out listOfResult)
{
//bla bla
}
versus
public List<string> c(out listOfResult)
{
List<string> list= new List<string>();
//bla bla
return list;
}
Are these two code snippets perfectly valid or is there any catch around the out keyword?
out keyword is handy when you need to return more than one value from function. Nice example is TryXXX methods, which return status of operation instead of throwing exceptions:
public bool TryParse(string str, out int value);
But I don't see any reason to use single out parameter with void methods... Simply return that value from your method. It will be much easier to use. Compare:
List<string> list;
GetList(out list); // confusing method name
With
List<string> list = GetList(); // nice name, one line of code
If getting of list could throw exceptions, then you can create method like this:
List<string> list;
if (TryGetList(out list)) // better than exception handling
{
// list was filled successfully
}
out parameters are quite handy when you need to return more than one value from a function.
e.g.
Return is a list of results, but you can use an out parameter to return an error message in the case when the list being returned is null.
It's a nice syntax to return multiple parameters. I personally think it's almost always better to model the return of the method as a "new object/class".
That would be:
class CResult
{
List<string> firstResult;
List<string> secondResult;
}
public CResult c()
{
// do something
return new CResult() {firstResult = ..., secondResult = ... };
}
You can see more things related to this approach here.
//out key word is used in function instead of return. we can use multiple parameters by using out key word
public void outKeyword(out string Firstname, out string SecondName)
{
Firstname = "Muhammad";
SecondName = "Ismail";
}
//on button click Event
protected void btnOutKeyword_Click(object sender, EventArgs e)
{
string first, second;
outKeyword(out first, out second);
lblOutKeyword.Text = first + " " + second;
}