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, when 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...
Related
Consider the following String:
String str = "XFB_PART~\XFB_IDF~\XFB_MODE~0\XFB_LOCALITEM~\XFB_REMOTEITEM~\XFB_MSG~tool\ soundgarden~\ASYNCHRONOUS~0\BROADCAST~0\XFB_LOCALAGT~"
What I would like to do is replace all the backslashes between XFB_MSG and ASYNCHRONOUS with commas (so every time you see a backslash, replace it with a comma).
Here's what I did:
stringBuffer = new StringBuffer(str);
for (int i = stringBuffer.indexOf("XFB_MSG"); i<stringBuffer.indexOf("ASYNCHRONOUS"); i++){
if(stringBuffer.charAt(i)=='\\'){
stringBuffer = stringBuffer.replace(i, i, ",");
}
}
Problem is, once the condition if (stringBuffer.charAt(i)=='\\') is met, the compiler keeps on entering and replacing the char even when i changes value and as a result I'm getting an infinite loop with commas being constantly inserted:
XFB_PART~\XFB_IDF~\XFB_MODE~0\XFB_LOCALITEM~\XFB_REMOTEITEM~\XFB_MSG~tool,,,,,,,,\ soundgarden~\ASYNCHRONOUS~0\BROADCAST~0\XFB_LOCALAGT~
Once again, the objective is to only replace all the backslashes between XFB_MSG and ASYNCHRONOUS and leave the rest of the string intact. The positions can change, and so can the value between those two parameters. So I have to search for them like that and try to find a way to replace the backslashes between them with commas.
Any idea why am I having an infinite loop, and if you happen to have a better way to do this, please do not hesitate to let me know.
Thank you.
I changed:
stringBuffer = stringBuffer.replace(i, i, ",");
to:
stringBuffer = stringBuffer.replace(i, i+1, ",");
and now it's working.
But I still don't understand why it's working now and why earlier I had an infinite loop.
I'm sure this is fairly simple, however I've tried googling the question but can't find an answer that fits my problem.
I'm playing around with string manipulation and one of the things I'm trying to do is get the first letter of each word. (And then place them all into a string)
I'm having trouble with registering each 'space' so that my If statement will be triggered. Here's what I have so far.
while (scanText.hasNext()) {
boolean isSpace = false;
if (scanText.hasNext(" ")) {isSpace = true;}
String s = scanText.next();
if (isSpace) {firstLetters += s + " ";}
}
Also, if there is a much better way to do this then please let me know
You can also split the original text by spaces, and collect the words.
String input = " Hello world aaa ";
String[] split = input.trim().split("\\s+"); // all types of whitespace; " +" to pick spaces only
// operate on "split" array containing words now: [Hello, world, aaa]
However using regexps here might be overkill.
Assuming that scanText is a Scanner object, you could use something like stated on the documentation:
Scanner s = new Scanner(input).useDelimiter("\\s+"); //regex for spaces
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
Can you split a string in Java without storing what has been split into variables? (Assignment requirement :()
I have tried things which worked on other programming languages however nothing I try seems to work:
(Attempting to see if the second item in a space delimited string (x) is +)
if ((x.split.(" ")).(1) = "+") {
// Do something
}
if ((x.split.(1).(" ")) = "+") {
// Do something
}
Well, what is returned is of type String[]. So if you know that there will be two items, you can reference it as an array..
if(x.split(" ")[1].equals("+"))
Extra Reading
You should look at String Comparison.
String.split returns an array, so this is how it could be done. Note the use of '.equals()'. In Java the == operator checks if the pointer value is the same.
if (x.split.(" ")[1].equals("+")) {
// Do something
}
(And of course this could throw an out of bounds exception if the split wouldn't make an array of size >= 2)
Newbie question comming up. Trying to get my head around JAVA.
How do I print out the content of the reference and not just their postition ? My program is ment to get some text in from the user, and print it out in a reverse order.
Here is my program (so far):
package myProgram;
import javax.swing.JOptionPane;
public class someRandomClass {
public static void main(String[] args) {
String word = JOptionPane.showInputDialog("Write som text here");
StringBuilder outPut = new StringBuilder();
for (int i = word.length()-1; i>=0; i--){
outPut.append(i);
}
System.out.println(outPut.toString());
}
}
I am greatfull for any help and tips! :)
In the line
outPut.append(i);
you are appending the value of your loop counter. You surely mean
outPut.append(word.charAt(i));
You seem to appending the integers instead of the appropriate characters. Try this instead:
outPut.append(word.substring(i, i + 1))
This way, the individual characters of word are appended to your StringBuilder. Note that the append method could also take a char as an argument, so you are also able to use word.charAt(i).
So, you want to emit the character at the position? Try using String.charAt.
outPut.append(word.charAt(i));
I'd probably avoid that and just index the char[] from String.toCharArray, though.
To be honest, I'd avoid doing the reversal loop manually to begin with... try something as follows:
final String word = JOptionPane.showInputDialog("Enter text below");
System.out.println(new StringBuilder(word).reverse());
StringBuilder.reverse should do the work for you (likely in a more efficient way, too). You also don't need to call toString manually, as println will do that for you.
I have a textfield called x.
When the textfield contains " ", I want to do something. If it does not, do something else.
I tried doing
String test = x.getText();
if(test.startsWith(" ")){buttonN.setForeground(Color.GRAY));}
else{buttonN.setForeground(Color.BLACK));}
but it didnt work. any suggestions
Why not use contains?:
if(x.getText().contains("\u0020"))
buttonN.setForeground(Color.GRAY);
else
buttonN.setForeground(Color.BLACK);
Although the aforementioned will work, it won't detect tabular spacing. That being said, I'd recommend using a regular expression instead:
if(Pattern.compile("\\s").matcher(x.getText()).find())
buttonN.setForeground(Color.GRAY);
else
buttonN.setForeground(Color.BLACK);
Reference.
If you just want to ensure if the text field is empty regardless of whether it contains space, tab, newline etc. use the following:
if(x.getText().trim().length() == 0){
buttonN.setForeground(Color.GRAY);
}else{
buttonN.setForeground(Color.BLACK);
}
The String.trim() removes any whitespace in the String.
The easiest solution for any verifycation of the getText() command is this:
If (field.getText().isEmpty()) {
buttonN.setForeground(Color.GRAY);
}
else {
buttonN.setForeground(Color.BLACK);
}
(Color.GRAY)) and (Color.BLACK)) end with 2 closing parenthesis, while only one was opened.
String test = x.getText();
if (test.startsWith (" "))
{
buttonN.setForeground (Color.GRAY);
}
else buttonN.setForeground (Color.BLACK);
Some spaces around parenthesis make the reading more convenient.