if statement should print string values
How do I print result from if statements in Java? This result should be assigned to some variable, that variable should print result in string. Currently, my code is like this. I want to store simple & extended into a single variable, so that i should able to call this variable anywhere in the program. There it should print "simple" or "extended".
if(loc[i]==1) {
System.out.println("simple");
}
else if(loc[i]>1) {
System.out.println("e开发者_Go百科xtended");
}
You mean like this:
String mode;
if(loc[i]==1)
mode = "simple";
else if(loc[i]>1)
mode = "extended";
else
mode = "error";
System.out.println(mode);
How about
String s = (loc[i]==1 ? "simple" : (loc[i]>1 ? "extended" : null));
If I understood you correctly you need following
private static final SIMPLE_STRING = "simple";
private static final EXTENDED_STRING = "extended";
if(loc[i]==1) {
System.out.println(SIMPLE_STRING );
}
else if(loc[i]>1) {
System.out.println(EXTENDED_STRING );
}
String type;
if( loc[i] == 1 )
{
type = "simple";
}
else if( loc[i] > 1)
{
type = "extended";
}
else
{
type = null;
}
// variable 'type' can now be used in the same block of code
System.out.println( type );
If you want to use this variable anywhere in your program, you will have to either declare the variable at a higher scope to be accessible or return this variable from this code block.
精彩评论