Using a string containing variables in JOptionPane
I am trying to build a string using "if" statements, and then using the built string to show in a JOptionPane.
//If the value is zero, don't show the line item
if (intLays > 0)
strBuiltOrder = "intSnickers + \"Snickers\" + \"\\n\"";
In the end there would be one line item for each variable that had a value greater than zero. However, the problem is, wh开发者_运维百科en I use it in JOptionPane, it outputs the literal.
intSnickers + \"Snickers\" + \"\\n\"
Is there anyway I can build a string to insert into JOptionPane, or is there another way to withhold variables from the JOptionPane if their value is zero?
Is there a reason why you escape quotes and backslashes? The following probably does what you expect:
if (intLays > 0) {
strBuiltOrder = intSnickers + "Snickers\n";
}
If you want to build a more complex string you can look into StringBuilder or StringBuffer objects.
Along my own presumption, maybe you were looking for this:
//If the value is zero, don't show the line item
if (intLays > 0)
strBuiltOrder = intSnickers + "\"Snickers\"" + "\"\\n\"";
I hope this helps, or at least points you in the right direction, when I understand more about the expected output I can try to help you out further.
Instead of using a String, try using a StringBuilder then you won't have problems with the syntax of that statement. So your code might be something like:
StringBuilder sb = new StringBuilder(...);
...
if (intLays > 0)
sb.append(intSnickers).append("Snickers\n");
Strings are immutable, so it better to use something like the StringBuilder or StringBuffer.
The solution was:
if (intSnickers > 0)
BuiltOrder.append( intSnickers + "Snickers" + "\n");
This is meant to concatenate a string and insert it into a JOptionPane. I am still sort of confused about why it works this way, instead of the way I have it, but, oh well...
精彩评论