Vince
Vince

Reputation: 2646

Is there a better way to write nested if statements in java

I'm writing a program where users can search for a directory, file, or both. Using checkboxes to determine what the user wants to do. Later down the road I may add another option, and the code my look ugly with all the nested if statements.

This is what I have so far:

if (directories.isSelected()) {
  if (files.isSelected()) {
    return file.isDirectory() || file.isFile();
  }
  return file.isDirectory();
} else {
  if (files.isSelected()) {
    return file.isFile();
  }
}

is there a more simpler way to do this?

Upvotes: 0

Views: 614

Answers (1)

Try this: return (directories.isSelected() && file.isDirectory()) || (files.isSelected() && file.isFile());

EDIT: That returns false if directories.isSelected() and files.isSelected() are both false. To make it return true in that case, stick a || !(directories.isSelected() || files.isSelected()) on the end.

Upvotes: 2

Related Questions