Leigh8347
Leigh8347

Reputation: 91

if & else statements

I'm looking for some help with a little problem I'm having. Basically i have a "if & else" statement in my app but I want to add another "if" statement that checks for a file then for certain line of text in that file. But I am unsure of how to do this.

here is what i i have

if(file.exists()) { 
                        do this
} else {
                        do this
}

Upvotes: 1

Views: 1570

Answers (3)

DNA
DNA

Reputation: 42617

Maybe you mean something like:

if(file.exists() && containsLine(file))
{
  // do something
}
else
{
  // do something else
}

public boolean containsLine(File f)
{
  // do the checking here
}

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1503779

It sounds like you either need:

if (file.exists() && readFileAndCheckForWhatever(file)) {
    // File exists and contains the relevant word
} else {
    // File doesn't exist, or doesn't contain the relevant word
}

or

if (file.exists()) {
    // Code elided: read the file...
    if (contents.contains(...)) {
        // File exists and contains the relevant word
    } else {
        // File exists but doesn't contain the relevant word
    }
} else {
    // File doesn't exist
}

or reversing the logic of the previous one to flatten it

if (!file.exists()) {
    // File doesn't exist
} else if (readFileAndCheckForWhatever(file)) {
    // File exists and contains the relevant word       
} else {
    // File exists but doesn't contain the relevant word
}

Upvotes: 5

malexmave
malexmave

Reputation: 1300

Unless I am missing something, couldn't you just be using else if?

else if((file.exists())&&(!file.contains(Whatever))) { ... }

File.contains would need to be exchanged for a function that actually checks the file, but you get the idea.

Upvotes: 2

Related Questions