0

I'm not really sure what this is called so it's hard to look it up and it is best if I show you what I'm trying to do.

I want to create a condional variable of sorts

String fileName = (if (this.filename != null) { return this.filename; } 
                   else { return "default value"; }); 

This should be pretty clear on what I'm trying to do. I want to use some sort of condition to set this variable based on another variables input, in this case whether or not it equals null or not.

4

4 に答える 4

7

Use the ternary operator. In my opinion, this is one of strategy in defensive programming.

String fileName = (this.filename != null? this.filename : "default value");
于 2013-03-12T03:35:20.163 に答える
5
String fileName = this.filename != null ? this.filename : "default value";
于 2013-03-12T03:35:13.777 に答える
1

Or, more verbose but (perhaps) easier to understand

String aFilename;
if (this.filename != null)
  aFilename = this.filename;
else
  aFilename = "Default Value";
return aFilename;

I prefer Careal's code but YMMV. Some find the ? operator complicated (especially in messy cases)

Also, when stepping though with the debugger this code will be way easier to see what happened.

于 2013-03-12T03:37:25.900 に答える
0

You can use ternary operator: boolean expression ? value1 : value2

String fileName = fileName == null ? "Default value" : this.filename;
于 2013-03-12T03:36:33.530 に答える