Else-part of code being executed, even if string.equals(otherstring) is true - try-catch

The problem with this code seems to be that the 'else' part of the if-statement is executed, even if the variables match (so 'if' is true). Any advice, please?
Thanks!
public void CheckInstalledDBVersion() throws NullPointerException, IOException {
try {
//TRY TO OPEN DATABASE AND READ VERSION
//WRITE VERSION TO InstalledDBversion
} catch(RuntimeException e) {
//IF TABLE COULD NOT BE QUERIED
//SET InstalledDBversion to Bogus value
InstalledDBversion = "00";
Log.d("RTE", ".. but we've catched it!");
} finally {
if (InstalledDBversion.equals(PackedDBversion)){
// Installed DBVersion == Packed DBVersion .. nothing happens
}
else
showDialog(DBCHECKFAILDIALOG);
initialiseDatabase = false;
copyDB();
}
}
So, when I execute, copyDB(); gets called even if InstalledDBversion.equals(PackedDBversion) == true

else
showDialog(DBCHECKFAILDIALOG);
initialiseDatabase = false;
copyDB();
Fixed indentation for you. copyDB is outside of the if/then/else block. Use an IDE with code formatting.

What lines are supposed to be included in the else block? the showDialog(DBCHECKFAILDIALOG) is only included. Are you missing a set of {} for the else block?

Related

Re-try-catch statement stuck in infinite loop

I have a piece of code wrapped in try-catch in order to catch an exception, but I want to re-try that piece of code until it is successful. I have added a loop based on this post. This works as far as looping the code, however it is an infinite loop. Once the code is successful and moves to the next page, the code is still looping and ends up failing because it is searching for a locator that is no longer available because the page has advanced to the next. My question is this: how do I break out of the loop once the code is successful?
int count = 0;
int maxTries = 1;
while (true)
{
try{
driver.FindElement(By.id("textbox").sendKeys("123");
driver.FindElement(By.id("submit").click();
driver.FindElement(By.id("catalog").click();
if(driver.getTitle().equals("Correct Page"))
{break;
}
}
catch(NoSuchElementException e)
{
if (++count == maxTries) throw e;
}
}
}
driver.FindElement(By.id("part1").click();
Maybe using an exception for this purpose is not the right route.
Instead of while (true), try while (!driver.getTitle().equals("Correct Page"))
Then within the loop, increment the count, check it against maxTries and break when it is exceeded

To check for infinite while loop. I am using a boolean variable

I am using the following code:
boolean continueProcessing = true;
boolean lastRecord = false;
while (continueProcessing) //can it be changed to while (continueProcessing == true), what's the advantage
{
if(refListItemItr.hasNext() || lastRecord)
{
continueProcessing = true;
lastRecord = false;
}
else
{
continueProcessing = false;
}
if(continueProcessing)
{
lSynonymListType = objFactory.createSynonymListType();
}
}
I suspect there is a scenario of infinite loop. How should I confirm that it does not happen.
The reason this will cause an infinite loop is that you keep checking if the next item exists, but you never actually call next() to retrieve it, so the internal pointer doesn't move along and you're just checking if there's a first item in the list.
Regardless, you're overcomplicating this. You should just be doing
while (refListItemItr.hasNext()){
Object item = refListItemItr.next(); // change Object to the item's type
// Presumably actually do something with the item here, which currently you're not...
}
Or, even more simply
for (Object o : refListItemItr){
// do stuff
}
And in answer to your other question, there is absolutely no difference between while(continueProcessing) and while (continueProcessing == true)

Case cannot fall through from one case label to another

Hi for some reason the break at the end of the "AndGroup" case is unreachable. I have tried to fix this with a goto and even moving the "return true" without result. Can anyone help me out?
switch (dependant[0])
{
case "AndGroup":
string[] sAndItems =
dependant[10].Split(
new char[] {','}, StringSplitOptions.RemoveEmptyEntries);
foreach (string sAndItem in sAndItems)
{
if (SC_Product.Dependancies.ContainsKey(sAndItem))
{
if (!SC_Product.Dependancies[sAndItem].DependantInstalled)
return false;
}
}
return true;
break;
case "Windows":
The break is unreachable because you have already exited via return true - there's no possible code branch by which the break can be executed.
Stuart is right "there's no possible code branch by which the break can be executed" , you may set a field but don't use return.

Return Value for "should cancel"

I have a method DoCleanUp(), which will ask user to proceed and then clear current workspace. It will return if user choose to cancel this process.
My question is, which signature is best to indicate a "cancel"?
bool DoCleanUp(); // return false to indicate canceled.
bool DoCleanUp(); // return true to indicate this method should be canceled.
void DoCleanUp(bool& cancel); // check parameter 'cancel' to see if this method was canceled.
UPDATE: As for the language, it's C++\CLI or C#.
UPDATE2: Now suppose I have to save a file in the DoCleanUp method. I'll prompt a dialog ask user whether to save/not save/cancel the file. Based on the answers, here is what I came up:
void DoCleanUp();
DialogResult AskToSaveFile(); // return yes/no/cancel
void DoCleanUp( bool saveFile );
Usage:
void DoCleanUp()
{
DialogResult result = AskToSaveFile();
if( result == DialogResult::Cancel ) return;
bool saveFile = (result == DialogResult::Yes) ? true : false;
DoCleanUp( saveFile );
}
Then by calling DoCleanUp(), you know user will have the opportunity to cancel;
By calling DoCleanUp(bool saveFile), you can control whether to save file without asking user.
Is that looks better?
This is a classic single responsibility problem.
The reason that you are unsure about the signature is that the method is doing 2 things.
I would create 2 methods:
bool CheckIfTheUserWantsToCancel()
void DoCleanUp()
EDIT
Based on the comments and edits to the question I would create a 3rd method:
void SaveFile()
The DoCleanUp would then first call CheckIfTheUserWantsToCancel, and then if not cancelled would call SaveFile.
IMHO this is much better than trying to remember that DoCleanUp with parameter false will save the file without asking the user, or was it the other way around?
Without more details I would say answer 1 is the best IMHO. Third is rather ugly since it requires more code for calling.
But maybe consider rewriting code to this
void CleanUp() {
switch (AskUser()) {
case ButtonOk: CleanUpDesk(); break;
case ButtonNo: break;
default:
case ButtonCancel: CancelCleanUpDesk(); break;
}
}
This seems to in the spirit of single responsibility. My code somehow breaks your problem into two steps: asking user and performing action.
I would use your 1 version.
bool DoCleanUp(); // return false to indicate canceled.
The assumption is, that it returns true when the cleanup is done. Returning false would indicate a 'Error' state. It might even make sense to return an int. In this case the convention usually is that 0 represents success and everything else is an error code.
Regardless of what you decide, document what your return values mean!
The confusing bit is the calling it DoSomething(), when it might not do anything. How about
if (QueryCleanup()) // boolean
DoCleanup(); // void
More verbose but clearer, even without seeing the declaration.
You should not use a boolean for statuses (or status messages). Create an Enum:
public Enum CleanupStatus
{
Ok = 0,
Cancel
}
This way it is more clear what the return value is ... and if you need to add more statuses, you can.
(This is all from Code Complete 2, you should read it if you haven't yet.)
You have two requests basically. The outer request is to create a new workspace. The inner request is to save the current workspace. You want to return true if the outer request continues and false if the outer request is aborted. The action of the inner request is not important to the outer request and so should be some kind of delegate/functor/closure.
Make a class to genericize this:
class YesNoCancel {
string question; // question to ask the user about the inner state
delegate doit; // function to call to
delegate dontdoit;
public:
YesNoCancel(string question, delegate doit, delegate dontdoit = null) {...}
bool run() {
switch (AskUser(question)) {
case ANSWER_YES: doit(); return true;
case ANSWER_NO: return true;
case ANSWER_CANCEL: if (dontdoit) dontdoit(); return false;
};
//usage
void NewWorkspace() {
if (m_workspace) {
YesNoCancel ync("Save current workspace?", saveworkspace);
if (!ync.run()) return;
}
// new workspace code
}
void CloseApp() {
YesNoCancel ync("Save current workspace?", saveworkspace);
if (ync.run()) ExitApplication();
}
I believe option three gives the most clarity. When you have the bool as a return type it is not immediately clear what it is used for.
I usually go with
bool DoCleanUp(); // Returns true if cancel
but mostly it depends on whether the calling code looks like this:
if (DoCleanUp()) {
// Do cancel up code
}
or:
if (DoCleanUp()) {
// Do non-cancel post clean up code
}
Basically I try to make my tests not have to use a ! or language equivilent as I find it hard to see.
I definitely would not do number 3.
I prefer the third signature, only because by looking at it (without any extra documentation), I can tell more about what the method does. I would call the argument something more explicit, like processCancelled, though.

What are the differences between if, else, and else if? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 2 years ago.
Improve this question
I am trying to discern the difference between
if
else
else if
When do you use them and when not?
I have a homework assignment with a ton of instances and I am running into code error due to not knowing the differences between each.
Can someone please define how to use these?
An if statement follows this sort of structure:
if (condition)
{
// executed only if "condition" is true
}
else if (other condition)
{
// executed only if "condition" was false and "other condition" is true
}
else
{
// executed only if both "condition" and "other condition" were false
}
The if portion is the only block that is absolutely mandatory. else if allows you to say "ok, if the previous condition was not true, then if this condition is true...". The else says "if none of the conditions above were true..."
You can have multiple else if blocks, but only one if block and only one (or zero) else blocks.
If-elseif-else can be written as a nested if-else. These are (logically speaking) equivalent:
if (A)
{
doA();
}
else if (B)
{
doB();
}
else if (C)
{
doC();
}
else
{
doX();
}
is the same as:
if (A)
{
doA();
}
else
{
if (B)
{
doB();
}
else
{
if (C)
{
doC();
}
else
{
doX();
}
}
}
The result is that ultimately only one of doA, doB, doC, or doX will be evaluated.
**IF** you are confused
read the c# spec
**ELSE IF** you are kind of confused
read some books
**ELSE**
everything should be OK.
:)
If, else and else if are all constructs to help 'branch' code. Basically, you employ them whenever you want to make a decision.
An example would be 'if it's sunny, I'll go outside. otherwise, I'll stay inside'
In code (ignoring the extra stuff)
if (sunny) {
goOutside();
}
else {
stayInside();
}
You CAN use 'else if' statements if you want to add 'additional' conditions. Extending the previous example, "if it's sunny, I'll go outside. If it's stormy, I'll go into the basement otherwise I'll stay inside"
In code
if (sunny) {
goOutside();
}
else if (stormy) {
goDownstairs();
}
else {
stayInside();
}
EDIT section:
Here is how you can write multiple ifs as and conditions. The following example can be written in at least two ways:
'If it's sunny and warm, go outside. If it's sunny and cold, do nothing'
if (sunny) {
if (warm) {
goOutside();
}
else if (cold) {
doNothing();
}
}
OR
if (sunny && warm) {
goOutside();
}
else if (sunny && cold) {
doNothing();
}
There's no "else if". You have the following:
if (condition)
statement or block
Or:
if (condition)
statement or block
else
statement or block
In the first case, the statement or block is executed if the condition is true (different than 0). In the second case, if the condition is true, the first statement or block is executed, otherwise the second statement or block is executed.
So, when you write "else if", that's an "else statement", where the second statement is an if statement. You might have problems if you try to do this:
if (condition)
if (condition)
statement or block
else
statement or block
The problem here being you want the "else" to refer to the first "if", but you are actually referring to the second one. You fix this by doing:
if (condition)
{
if (condition)
statement or block
} else
statement or block
Dead Simple Pseudo-Code Explanation:
/* If Example */
if(condition_is_true){
do_this
}
now_do_this_regardless_of_whether_condition_was_true_or_false
/* If-Else Example */
if(condition_is_true){
do_this
}else{
do_this_if_condition_was_false
}
now_do_this_regardless_of_whether_condition_was_true_or_false
/* If-ElseIf-Else Example */
if(condition_is_true){
do_this
}else if(different_condition_is_true){
do_this_only_if_first_condition_was_false_and_different_condition_was_true
}else{
do_this_only_if_neither_condition_was_true
}
now_do_this_regardless_of_whether_condition_was_true_or_false
I think it helps to think of the "else" as the word OTHERWISE.
so you would read it like this:
if (something is true)
{
// do stuff
}
otherwise if (some other thing is true)
{
// do some stuff
}
otherwise
{
// do some other stuff :)
}
if (condition)
{
thingsToDo()..
}
else if (condition2)
{
thingsToDoInTheSecondCase()..
}
else
{
thingsToDoInOtherCase()..
}
you can think of the if and else as a pair, that satisfies two actions for one given condition.
ex: if it rains, take an umbrella else go without an umbrella.
there are two actions
go with an umbrella
go without an umbrella
and both the two actions are bound to one condition, i.e is it raining?
now, consider a scenario where there are multiple conditions and actions, bound together.
ex: if you are hungry and you are not broke, enjoy your meal at kfc, else if you are hungry but you are broke, try to compromise, else if you are not hungry, but you just want to hangout in a cafe, try startbucks, else do anything, just don't ask me about hunger or food. i have got bigger things to worry.
the else if statement to to string together all the actions that falls in between the if and the else conditions.
They mean exactly what they mean in English.
IF a condition is true, do something, ELSE (otherwise) IF another condition is true, do something, ELSE do this when all else fails.
Note that there is no else if construct specifically, just if and else, but the syntax allows you to place else and if together, and the convention is not to nest them deeper when you do. For example:
if( x )
{
...
}
else if( y )
{
...
}
else
{
...
}
Is syntactically identical to:
if( x )
{
...
}
else
{
if( y )
{
...
}
else
{
...
}
}
The syntax in both cases is:
if *<statment|statment-block>* else *<statment|statment-block>*
and if is itself a statment, so that syntax alone supports the use of else if
if (numOptions == 1)
return "if";
else if (numOptions > 2)
return "else if";
else
return "else";
The syntax of if statement is
if(condition)
something; // executed, when condition is true
else
otherthing; // otherwise this part is executed
So, basically, else is a part of if construct (something and otherthing are often compound statements enclosed in {} and else part is, in fact, optional). And else if is a combination of two ifs, where otherthing is an if itself.
if(condition1)
something;
else if(condition2)
otherthing;
else
totallydifferenthing;
The if statement uses the results of a logical expression to decide if one of two code blocks will be executed.
With this code
if (logical expression) {
code block 1;
} else {
code block 2;
}
if the logical expression is true, only the statements in code block 1 will be executed; if false, only the statements in code block 2.
In the case that there are multiple similar tests to be done (for instance if we are testing a number to be less than zero, equal to zero or more than zero) then the second test can be placed as the first statement of the else code block.
if (logical expression 1) {
code block 1;
} else {
if (logical expression 2) {
code block 2;
} else {
code block 3;
}
}
In this case, code block 1 is executed if logical expression 1 is true; code block 2 if logical expression 1 is false and logical expression 2 is true; code block 3 if both logical expressions are false.
Obviously this can be repeated with another if statement as the first statement of code block 3.
The else if statement is simply a reformatted version of this code.
if (logical expression 1) {
code block 1;
} else if (logical expression 2) {
code block 2;
} else {
code block 3;
}
The else if can be used in conjunction with 'if', and 'else' to further break down the logic
//if less than zero
if( myInt < 0){
//do something
}else if( myInt > 0 && myInt < 10){
//else if between 0 and 10
//do something
}else{
//else all others
//do something
}
Those are the basic decision orders that you have in most of the programming language; it helps you to decide the flow of actions that your program is gonna do.
The if is telling the compiler that you have a question, and the question is the condition between parenthesis
if (condition) {
thingsToDo()..
}
the else part is an addition to this structure to tell the compiler what to do if the condition is false
if (condition) {
thingsToDo()..
} else {
thingsToDoInOtherCase()..
}
you can combine those to form a else if which is when the first condition is false but you want to do another question before to decide what to do.
if (condition) {
thingsToDo()..
} else if (condition2) {
thingsToDoInTheSecondCase()..
}else {
thingsToDoInOtherCase()..
}
If and else if both are used to test the conditions.
I take case of If and else..
In the if case compiler check all cases Wether it is true or false.
if no one block execute then else part will be executed.
in the case of else if compiler stop the flow of program when it got false value. it does not read whole program.So better performance we use else if.
But both have their importance according to situation
i take example of foor ordering menu
if i use else if then it will suit well
because user can check only one also.
and it will give error
so i use if here..
StringBuilder result=new StringBuilder();
result.append("Selected Items:");
if(pizza.isChecked()){
result.append("\nPizza 100Rs");
totalamount+=100;
}
if(coffe.isChecked()){
result.append("\nCoffe 50Rs");
totalamount+=50;
}
if(burger.isChecked()){
result.append("\nBurger 120Rs");
totalamount+=120;
}
result.append("\nTotal: "+totalamount+"Rs");
//Displaying the message on the toast
Toast.makeText(getApplicationContext(), result.toString(), Toast.LENGTH_LONG).show();
}
now else if case
if (time < 12) {
greeting = "Good morning";
} else if (time < 22) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
here only satisfy one condition..
and in case of if multiple conditions can be satisfied...
What the if says:
Whether I'm true or not, always check other conditions too.
What the else if says:
Only check other conditions if i wasn't true.

Resources