How can recursively replace all catenations in toString method to StringBuilder for Java? Is there such a plugin in eclipse?
For example:
Replace it:
return "AccountAddresses ["
+ ", corporateAddresses=" + CommonHelper.isNotNull(corporateAddresses)
+ ", corporateDeliveryMinimum=" + corporateDeliveryMinimum
+ ", depot=" + CommonHelper.isNotNull(depot)
+ ", depotDeliveryMinimum=" + depotDeliveryMinimum
+ ", preSelectedId=" + preSelectedId
+ ", residentialAddresses=" + CommonHelper.isNotNull(residentialAddresses)
+ ", residentialDeliveryMinimum=" + residentialDeliveryMinimum
+ "]";
at this:
return new StringBuilder("AccountAddresses [")
.append(", corporateAddresses=").append(CommonHelper.isNotNull(corporateAddresses))
.append(", corporateDeliveryMinimum=").append(corporateDeliveryMinimum)
.append(", depot=").append(CommonHelper.isNotNull(depot))
.append(", depotDeliveryMinimum=").append(depotDeliveryMinimum)
.append(", preSelectedId=").append(preSelectedId)
.append(", residentialAddresses=").append(CommonHelper.isNotNull(residentialAddresses))
.append(", residentialDeliveryMinimum=").append(residentialDeliveryMinimum)
.append("]").toString();
It's a builtin command of Eclipse.
Click on one of the quotation marks (") in your String concatenation.
Bring the Quick Fix menu (Hit Ctrl + 1 on the keyboard).
Select Use 'StringBuilder' for String concatenation.
Magic! Your
return "foo" + "bar";
changed to
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("foo");
stringBuilder.append("bar");
return stringBuilder.toString();
I haven't heard of an Eclipse plugin for this - so feel free to ignore this off topic answer - but IntelliJ has an "intention" that will do it for you (at least in 10.0 it does). There is a community edition available if you want to give it a shot.
Do a regex search and replace :
", ([a-zA-z0-9]+)=" \+ CommonHelper\.isNotNull\(([a-zA-z0-9]+)\) // Find this
append(", $1=").append(CommonHelper.isNotNull($2)) // and replace with this
It is not complete, but you get the idea.
Why dont you override the toString method in your class , and implement the stringbuilder append.
I don't think any plugin would do that for you... this would be useless anyways : the Java compiler will do it better than anyone can (and if "StringBuilder" is ever replaced by something better, the Java compiler will be able to use this "something better" if you do not explicitely use a StringBuilder).
Related
I want the "Module Code = " and "Result = " to be separated by a tab but whenever I run the code below it literally just outputs
"Module Code = Biology\tResult = 40.0"
public String toString()
{
return "Module Code = " + moduleCode + "\t" + "Result = " + result;
}
The problem is that you're viewing the value of the produced string in the BlueJ window. That window is good for debugging purposes, but it won't exhibit the same behavior that a proper output device would, especially with respect to characters such as newline, tabulation, etc. Those characters will still appear with their escape sequences, just like you typed them in your source code.
In other words, your toString() method is fine and it works as intended. If you want to see its results formatted properly, don't view them using BlueJ -- print them somewhere else. The console is a good choice:
System.out.println(module.toString());
Why won't “\t” create a new line?
well, that is because “\t” is a tabulation not a new line “\n”
if you need a new line try instead
return "Module Code = " + moduleCode + "\n" + "Result = " + result;
How can I automatically print without poping up dialog box or automatically accept print dialog? Here is some of my code:
if ("OUT".equals(rs.getString("empattendance"))) {
String date = dft.format(dNow);
String time = tft.format(dNow);
textArea.setText(date + "\n" + "\n" +
fullname +"\n" +
"Time In: " + time + "\n" +
"Status: "+ statusin +
"\n" +
"\n" +
"____________________\n" +
" Sign by Supervisor");
try {
//printing
Boolean complete = textArea.print();
if(complete){
}
else{
}
} catch (PrinterException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}
and here's the screenshot of the current behaviour.
thanks
When I look at your code I have few thoughts before answer.
1) Do not use String. Better for comparing stuff is Enumerators I believe.
2) If you would like to set text to textArea previously create some method using StringBuilder for example which will be creating the String you would like to set. Joshua Bloch says
Item 15: minimize mutability (...) If a client requires performing expensive multi-stage operations on your class, expose them as primitive methods, or provide a mutable companion class (like StringBuilder for String).
And take a look at this topic for more.
3) To print data from textArea if I were you I would try to use this.
I believe that would help you
I have this statement:
s = s + "Id: " + lc.getID() + " Name: " + lc.getName() + "\n"
+ " Phone Number: " + lc.getPhone() + " Email: " + lc.getEmail() + "\n"
+ " Description: " + lc.getDescription() + "\n\n"
that prints this out:
Id: 1 Name: Eric
Phone Number: 8294038 Email: foo#gmail.com
Description: Cool guy Eric
I want to Bold only the titles (Id, Name, etc).
I tried this:
s = s + Html.fromHtml(" <b> Id: </b>" + lc.getID() + " <b> Name: </b>" + lc.getName() + "\n"
+ " Phone Number: " + lc.getPhone() + " Email: " + lc.getEmail() + "\n"
+ " Description: " + lc.getDescription() + "\n"
+ "\n\n");
But not only does it not bold, but it takes away the new lines (\n). Any ideas on how to get this done? Thanks.
Html.fromHtml() returns a Spanned object, designed to be put directly into a TextView or similar widget.
A Spanned is not a String.
By doing s = s + Html.fromHtml(...), you are saying "please parse this HTML into a Spanned, then throw out all the formatting to give me a String that I can concatenate onto some other String". That's not what you want -- you want to keep the formatting. But a Java String does not have formatting, and so ordinary string concatenation has no way to keep it.
Beyond that, as Manishika pointed out, newlines are ignored in HTML anyway, as you use HTML elements for vertical whitespace.
Your options include:
Generate a complete HTML snippet -- including whatever it is you are trying to concatenate it to -- and then use Html.fromHtml() on the entire thing. You may wish to use a template engine (e.g., jmustache) for that, or String.format(). Or, use StringBuilder, rather than lots of + operations (less memory churn, faster performance). Be sure to use <br/> or <p> for your line breaks/paragraph delimiters.
Use SpannableStringBuilder to assemble the string and its formatting from component parts.
Use TextUtils.concat(s, Html.fromHtml(...)) instead of s + Html.fromHtml(...), as concat() will maintain the spans that implement the formatting. While the implementation of Spanned returned by fromHtml() is not a String, both it and String are a CharSequence, and hence work with concat().
It will require a little bit of parsing on your end, but you definitely want to look into SpannableStrings.
For example, let's say I have the following string:
String s = "How now brown cow";
I would then turn it into a SpannableString by simply feeding the string to the constructor as follows:
SpannableString ss = new SpannableString(s);
From there you need your stylization with the spanned area. For this, I'll just use SubscriptSpan, though if you wish to make your own you can simply make your own class extending CharacterStyle and override the updateDrawState(TextPaint ds) method. The following is how you can set you span:
/ *
* the first argument is the span effect you want, the second and third
* are the start and end indices, respectively, and the last argument is
* for setting a flag, which you probably won't need.
*/
ss.setSpan(new SubscriptSpan(), 0, 2, 0);
And now you can just put your string straight into the TextView and it should appear how you want, like so:
myTextView.setText(ss);
This question already has answers here:
StringBuilder vs String concatenation in toString() in Java
(20 answers)
Closed 8 years ago.
I've read about StringBuilder class in Java and I'm wondering, what is more efficient way to do some task:
Using "+" concatenation:
String result = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<entry xmlns=\"http://www.w3.org/2005/Atom\" xmlns:y=\"http://api.yandex.ru/yaru/\">"
+ "<title>" + (et_title.getText().toString()) + "</title>" +
"<y:access>"+ privacymode +"</y:access>" +
"<category scheme=\"urn:ya.ru:posttypes\" term=\"link\"/>"
+ "<y:meta>" + "<y:url>" + (et_link.getText().toString()) + "</y:url>" +
"</y:meta>" +
"<content>" + signature_select() + "</content>"
+ "</entry>";
or
StringBuilder sb = new StringBuilder();
sb.append( "<?xml version=\"1.0\" encoding=\"utf-8\"?>")
.append("<entry xmlns=\"http://www.w3.org/2005/Atom\" xmlns:y=\"http://api.yandex.ru/yaru/\">")
.append("<title>")
.append(et_title.getText().toString())
.append("</title>")
.append("<y:access>"+ privacymode +"</y:access>")
.append( "<category scheme=\"urn:ya.ru:posttypes\" term=\"link\"/>")
.append("<y:meta>" + "<y:url>" + (et_link.getText().toString()) + "</y:url>" + "</y:meta>")
.append( "<content>" + signature_select() + "</content>")
.append("</entry>");
String result = sb.toString();
This looks to be worrying about premature optimization. If this is a one-off bit of code and not being called within a tight loop, why worry about optimizing?
Having said that, most often the xml text would be found in a text file and not hard-coded in the program, and then you'll use a loop and a StringBuilder, i.e.,
StringBuilder xmlSb = new StringBuilder();
Scanner xmlScanner = new Scanner(Foo.class.getResourceAsStream(RESOURCE));
while (xmlScanner.hasNextLine()) {
xmlSb.append(xmlScanner.nextLine());
}
if (xmlScanner != null) {
xmlScanner.close();
}
// parse and use your xml text here
Edit: Looks like the Java compiler will optimize the String concatenation (+) version, so both versions will have the same performance, with the advantage to the first one being more readable.
Leaving my previous answer for historic purposes.
Thanks for the comments!
The StringBuilder version is better.
I'd also break the other concatenations you have in the StringBuilder version, like for example:
.append("<y:access>"+ privacymode +"</y:access>")
as:
.append("<y:access>")
.append(privacymode)
.append("</y:access>")
The biggest advantage of using StringBuilder is that you avoid allocating new Strings for each concatenation, whereas StringBuilder will only allocate and resize its internal char array when necessary. It would be even better if you knew the size of the final string. Then you could initialize the StringBuilder with its final size and avoid any extra memory allocation.
I am using this code to separate the next line and giving space.
String sms="Name:"+name+ System.getProperty ("line.separator")+System.getProperty
("line.separator")+"ContactNumber:"+contactnumber+ System.getProperty
("line.separator")+"Quantity:"+quantity+System.getProperty
("line.separator")+"Number.of.Pcs:"+noofpieces+System.getProperty
("line.separator")+"Date and Time:"+dateandtime
+System.getProperty ("line.separator")+"Delivary
Address:"+deliveryaddress;
You could use a StringBuilder instance and then use the new line operator appended to the StringBuilder. For example:
StringBuilder sb = new StringBuilder();
sb.append("Name: ").append(name);
sb.append("\n"); // for a new line.
Whatever the case, I would strongly recommend that you use a StringBuilder to append to a very large String.
In addition, you could also use System.lineSeparator(); However, that may only work in Java with the JVM with Java 7 and not in Android (so I would definitely check that out.)
String sms= "Name:" + name
+ "\nContactNumber:" + contactnumber
+ "\nQuantity:" + quantity
+ "\nNumber.of.Pcs:" + noofpieces
+ "\nDate and Time:" + dateandtime
+ "\nDelivary Address:" + deliveryaddress;
Using System.getProperty("line.separator") is a good practice as it will give you code that could be reused on another platform. To simplify your code, you can use TextUtils.join :
String sms = TextUtils.join(System.getProperty("line.separator"),
new String[] {
"Name:" + name ,
"ContactNumber:" + contactnumber,
...});
You could also use this solution
String format = "Name: %s%n%nContactNumber: %s%nQuantity: %s%nNumber.of.Pcs: %s%nDate and Time: %s%nDelivery Address: %s";
String sms = String.format(format, name, contactnumber, quantity, noofpieces, dateandtime, deliveryaddress);
The explanation of the format placeholders you find in the Javadoc for java.util.Formater