How do I concatenate strings in NETBEANS with + signs and escape codes? - java

Here's what I'm trying to do:
String output = "If you borrow" + currencyFormatter.format(loanAmount);
+" at an interest rate of" + rate + %;
+"\nfor" + years;
+",you will pay" + totalInterest + "in interest.";

Take out the semicolons before the end of your concatenation.
String output = "If you borrow" + currencyFormatter.format(loanAmount)
+" at an interest rate of" + rate + "%"
+"\nfor" + years
+",you will pay" + totalInterest + "in interest.";
I also recommend that you move the concatenation operator to the end of the line rather than the start of the line. It's a minor stylistic preference...
String output = "If you borrow" + currencyFormatter.format(loanAmount) +
" at an interest rate of" + rate + "%" +
"\nfor" + years +
",you will pay" + totalInterest + "in interest.";
Finally, you may notice that you are missing some white-spaces when you try printing that string. The String.format method helps with that (also see the documentation for Formatter). It's also faster than doing lots of concatenations.
String output = String.format(
"If you borrow %s at an interest rate of %d%%\nfor %d years, you will pay %d in interest.", currencyFormatter.format(loanAmount), rate, years, totalInterest
);

Related

cannot find symbol method append (String)

I don't get it why it says it cannot find symbol append.
do i need to use Stringbuffer? i got this code on a tutorial for receipts from youtube, and the uploader disabled comments so I can't ask him directly. please help me. Im still an amateur at java.
Tell me if I need to post my whole code or what code would you want to see to see errors. thanks in adv.
Calendar timer = Calendar.getInstance();
timer.getTime();
SimpleDateFormat tTime = new SimpleDateFormat("HH:mm:ss");
tTime.format(timer.getTime());
SimpleDateFormat Tdate = new SimpleDateFormat("dd-MMM-yyyy");
Tdate.format(timer.getTime());
jtxtReceipt.append("\ Water Station Receipt:\n" +
"Reference:\t\t\t" + refs +
"\n=========================================\n" +
"Mineral:\t\t\t" + jtxtMineral.getText() + "\n\n" +
"Purified:\t\t\t" + jtxtPurified.getText() + "\n\n" +
"Travel:\t\t\t" + jtxtTravel.getText() + "\n\n" +
"VAT:\t\t\t" + jtxtVat.getText() + "\n"+
"\n========================================\n" + "\n" +
"Tax:\t\t\t" + jtxtTax2.getText() + "\n" +
"Subtotal:\t\t\t" + jtxtSubTotal.getText() + "\n" +
"Total:\t\t\t" + jtxtTotal.getText() + "\n" +
"===========================================" +
"\nDate:" + Tdate.format(timer.getTime()) +
"\ntTime:" + tTime.format(timer.getTime()) +
"\n\t\tThank you ");
The append method doesn't exist in the String class. You can either user a StringBuilder to do the job, or if it's a light concatenation, just use the + operator
The append method doesn't work on TextField Palette. So, if You're on TextField Palette, replacing that with TextArea Palette should solve the problem.

I'm unsure why the newline character isn't affecting what's printed [duplicate]

This question already has answers here:
PrintWriter to print on next line
(3 answers)
Closed 4 years ago.
I am writing a simple program to keep track of my fuel consumption. I am trying to figure out why the newline character is not outputting
to the file, but the other fields are.
PrintWriter fuelLog = new PrintWriter(new FileWriter("FuelLog.txt", true));
fuelLog.println("New Trip");
miles = JOptionPane.showInputDialog("Please enter trip miles...");
dollars = JOptionPane.showInputDialog("Please enter cost to refuel...");
gallons = JOptionPane.showInputDialog("Enter the gallons used on the trip...");
fuelLog.println("Miles on trip: " + miles + "\n" +
"Cost: $" + dollars + "\n" +
"Gallons used: " + gallons);
fuelLog.close();
The output to my file ends up being something like this for example:
Miles on trip: 270.67Cost: $33.76Gallons used: 11.567
The desired output to the file I am looking for is:
Miles on trip: 270.67
Cost: $33.76
Gallons used: 11.567
The newline character(s) is (are) platform dependent, and may very well be \r\n on your platform. You can avoid the problem by using printf with the %n special character that gets translated to the proper newline in your platform. As a side effect, it can also help clean up your code and avoid all those string concatinations:
fuelLog.printf("Miles on trip: %s%n" +
"Cost: $%s%n" +
"Gallons used: %s%n", miles, dollars, gallons);

Regex expression taking too much time

I have the below regex expression in a Java code, it is taking a good deal of time to complete on some cases. Is there a way to improve it?
String decimal = "([0-9]+(\\.[0-9]+)?[/-]?)+";
String units = "(in|ft)\\.?";
String unitName = "(cu\\.? *ft|gauge|watt|rpm|ft|lbs|K|GPF|btu|mph|cfm|volt|oz|pounds|dbi|miles|amp|hour|kw|f|degrees|year)";
sizePattern.add(Pattern.compile("(?i)" + decimal + " *" + units + " *x? *" + decimal + " *" + units + " *x? *" + decimal + " *" + units + ""));
sizePattern.add(Pattern.compile("(?i)" + decimal + " *" + units + " *x? *" + decimal + " *" + units));
sizePattern.add(Pattern.compile("(?i)" + decimal + " *x *" + decimal + " *" + units));
sizePattern.add(Pattern.compile("(?i)" + decimal + "( *" + units + ")"));
sizePattern.add(Pattern.compile("(?i)" + decimal + "( *sq?\\.?)( *ft?\\.?)"));
sizePattern.add(Pattern.compile("(?i)" + decimal + " *" + unitName));
sizePattern.add(Pattern.compile("(?i)" + decimal + "(d)"));
sizePattern.add(Pattern.compile("(?i)" + decimal + "( *(%|percent))"));
sizePattern.add(Pattern.compile("(?i)" + decimal));
for (Pattern p : sizePattern)
{
ODebug.Write(Level.FINER, "PRD-0079: Using pattern = " + p.pattern());
m = p.matcher(_data);
while (m.find())
{
ODebug.Write(Level.FINER, " Got => [" + m.group(0) + "]");
this.Dimensions.add(m.group(0));
_data = _data.replaceAll("\\Q" + m.group(0) + "\\E", ".");
m = p.matcher(_data);
}
}
String causing the issue:
Micro-Induction Cooktop provides the best in cooktop performance, safety and efficiency. Induction heats as electricity flows through a coil to produce a magnetic field under the ceramic plate. When a ferromagnetic cookware is placed on the ceramic surface, currents are induced in the cookware and instant heat is generated due to the resistance of the pan. Heat is generated to the pan only and no heat is lost. As there are no open flames, inductions are safer to use than conventional burners. Once cookware is removed, all molecular activity ceases and heating is stopped immediately.Flush surface for built-in or freestanding applicationDual functions: Cook and Warm7 power settings (100-300-500-700-900-1100-1300W)* The 2 lowest power settings cannot be actually achieved, but are ""simulated"":100W = 500W intermittently heat for 2 seconds and stop for 8 seconds300W = 500W intermittently heat for 6 seconds and stop for 4 seconds13 Keep Warm settings (100-120-140-160-180-190-210-230-250-280-300-350-390F)Touch sensitive panel with control lockUp to 8 hours timerMicro-crystal ceramic plateAutomatic pan detectionLED panelETL/ETL-Sanitation/FCC certified for household or commercial useHome Depot Protection Plan:
Assuming your _data is long, it's not the matching what takes the time, but rather the assignment
_data = _data.replaceAll("\\Q" + m.group(0) + "\\E", ".");
which is O(n**2) in terms of the string length. Just don't do it.
You could do it simpler with
_data = _data.replace(m.group(0), ".");
but just don't do it. Do you need a reduced _data at the end? If so, use a single replaceAll per pattern (it uses a StringBuffer internally and is only linear in the size of the string).
Additionally:
Use non-capturing groups.
Consider recycling the Matcher by using reset(CharSequence) and usePattern(Pattern).
Consider combining all the patterns into one. As all of them start the same, it could be quite efficient.
Your decimal can probably get slow in case there's no match. Leaving out the optional part, you get "([0-9]+)+" which can backtrack needlessly a lot. Consider using atomic groups.

.split("|") doesn't return the correct string [duplicate]

This question already has answers here:
Splitting a Java String by the pipe symbol using split("|")
(7 answers)
Closed 7 years ago.
I'm sending this string from the client to the server:
Ar|0.04107356|-0.31299785|-0.9991561
That string is as printed out by the server - So it is correct.
"Ar" is the packet name, and the values are the velocity of an arrow that the archer is going to shoot.
So to get those values, I'm using
String[] values = str.split("|");
And then
a.shoot(Float.valueOf(values[1]), Float.valueOf(values[2]), Float.valueOf(values[3])); //a is an archer
The problem is, values1, values[2], and values[3] seem to be corrupt or unrecognizable.
My full code is this:
public void handleMessage(String str){
System.out.println(str);
String[] values = str.split("|");
if (values[0].contains("Ar")){
System.out.println("X: " + values[1] + " Y: " + values[2] + " Z: " + values[3]);
}
System.out.println("Vals: " + values[0] + " " + values[1] + " " + values[2] + " " + values[3]);
if (true) return; //Returning so I can analyze de-bug messages without crashes.
for (Archer a : GameServer.archers){
a.shoot(Float.valueOf(values[1]), Float.valueOf(values[2]), Float.valueOf(values[3]));
}
When I print out the "Vals" message, it comes out like this:
Vals: A r |
What is going wrong here?
The horizontal bar has a special meaning in Java regular expressions which you must escape in order to use as a literal:
String[] values = str.split("\\|");

How can I format in java?

This is what I currently have so far
public String toString() {
return this.make + " " + this.model + " " + this.year + " $"
+ this.price + " " + this.mpg;
}
I need to format it to these specifications
Make: left-justified and will be no more than 10 characters long
Model: left-justified starting in column 11 and will be no more than 10 characters long
Year: left-justified and starting in column 21
Price: will be output according to the following money format $99,999.00
MPG: will be output according to the following format: 99.0.
Please help, I'm lost.
Thanks
String.format() is useful for this. It functions similarly to printf in C if you have used it. See http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#format%28java.lang.String,%20java.lang.Object...%29 and http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax
look here:
http://examples.javacodegeeks.com/core-java/lang/string/java-string-format-example/
According to the article, you gotta format like this
return String.format("%s %s %s $%s %s",this.make,this.model,this.year,this.price,this.mpg);

Categories