Is there a way to include a simple if statement inside a Java String passed as argument to a function, like the following example
int TotalFiles = 3;
JOptionPane.showMessageDialog(frame,
"Created " + TotalFiles + " file" + (if(TotalFiles>1){"s"}) + ".");
You can use a ternary (or conditional) operator :
"Created " + TotalFiles + " file" + (TotalFiles > 1 ? "s" : "") + "."
Side comment: non-constant variables in Java start in lower case, so totalFiles
.
尝试: (totalFiles>0 ? "s" : "sometThingElse")
Use a ternary operator.
JOptionPane
.showMessageDialog(
frame,
"Created " + TotalFiles + " file" + (TotalFiles > 0 ? "s": "") + "."
);
I also recommend:
camelBack
as opposed to CamelCase
String
formats for easier to read/maintain formatting Yes, using Ternary operators.
JOptionPane.showMessageDialog(frame, "Created " + TotalFiles + " file" + (TotalFiles > 0 ? "s" : "") + ".");
Ternary takes an expression such as (TotalFiles > 0)
, compares it, and if it is true returns the value after the ?
, otherwise returns the value after :
This is equivilant to designing a private method that returns a string based on the expression:
private String isMultipleFiles( int totalFiles )
{
if( totalFiles > 0 )
return "s";
else
return "";
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.