new line in java - java

Java newbie here, I'm having trouble setting a new line in this code:
String FnameTextboxText = FnameTextbox.getText();
String LastnameTextboxText = LastnameTextbox.getText();
String CourseTextboxText = CourseTextbox.getText();
Summary.setText("Firstname:" + " " + FnameTextboxText + "\nLastname:" + " " + LastnameTextboxText + "\nCourse:" + " " + CourseTextboxText);
Also tried something like: "\n" + "Lastname" But its no good.
Do you have any idea on how to make new lines. So that it'll look like this;
Firstname: x
Lastname: y
Course: Z
Using netbeans 6.8. On windows.

I guess you need to use TextArea.

First, use TextArea
Second, test using \r or \n or \r\n
Sometimes, people use \n to make new line and sometimes, like me, use \r\n to make new line

Related

Can't add a newline when repeatedly appending onto a string

I am trying to write to a text document with a specific format. Here's what I have right now.
String line = "";
double totalCost = 0;
Node curr = summary.head.next;
while(curr!=summary.tail)
{
line += [an assortment of strings and variables] +"\r";
totalCost += PRICELIST.get(curr.itemName)*curr.count;
curr = curr.next;
}
write.printf("%s" + "%n", line);
This is what the part adding onto line actually looks like.
"Item's name: " + curr.itemName + ", Cost per item: " + NumberFormat.getCurrencyInstance().format(PRICELIST.get(curr.itemName)) +
", Quantity: " + curr.count + ", Cost: " + NumberFormat.getCurrencyInstance().format(PRICELIST.get(curr.itemName)*curr.count) + "\r";
I've tried that with a newline character too. Before I had it working when the print statement was inside the loop meaning it only wrote one line at a time. I want to do it this way because I will have multiple threads writing to this file and this way any thread will not hold the lock for as long.
If using Java 7 or later you can use System.lineSeparator()
Use System.getProperty("line.separator") instead of "\r"
Cache ir for efficiency though.
First of all don't use
while(..){
result += newString
..
}
inside loop. This is very inefficient especially for long texts because each time you call
result += newString
you are creating new String which needs to copy content of result and append to it newStrint. So the more text you processed so far, the more it has to copy so it becomes slower.
Instead use
StringBuilder sb = new StringBuilder();
while(..){
sb.append(newString);
}
result = sb.toString.
which in your case should be something more like
sb.append("Item's name: ").append(curr.itemName)
.append(", Cost per item: ").append(NumberFormat.getCurrencyInstance().format(PRICELIST.get(curr.itemName)))
.append(", Quantity: ").append(curr.count )
.append(", Cost: ").append(NumberFormat.getCurrencyInstance().format(PRICELIST.get(curr.itemName) * curr.count))
.append(System.lineSeparator());
Also instead of
write.printf("%s" + "%n", line);
you should use simpler version, which is
write.println(line);
which automatically add line separator based on OS.
You can also try to use \n\r in combination. This helped in one of my projects.

Statements ignored outside while loop?

Hello this problem has been bugging me since a week I searched everywhere in vain. I have this code
................
while ((str = buff.readLine()) != null) {
String[] line = str.split(";");
String part1 = line[0];
String part2 = line[1];
String part3 = line[2];
String part4 = line[3];
String part5 = line[4];
if (c.equals(part3)) {
st = st + part1 + ";" + part2 + ";" + part3 + ";" + part4 + ";" + part5;
System.out.println(part1 + ";" + part2 + ";" + part3 + ";" + part4 + ";" + part5 + "\n");
fich1_tampon.write(st);
fich1_tampon.flush();
fich1_tampon.newLine();
++i;
}
}
System.out.println("F;" + i);
fich1_tampon.close();
buff.close();
}
the "System.out.println("F;" + i);" is ignored I don't know why. The code is very long but basically I'm looking for lines that have a certain String that was put in c and I'm writing those line in another file.
The result on my consoleis like this :
E;2014/02/19 20:21:06
File already exists.
N;2000;PU;Promotion iphone;232425
N;2001;PU;Promotion dell;232426
N;2002;PU;Promotion samsung;23242
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at LireFichierDecouper.decouper(LireFichierDecouper.java:70)
at Main2.main(Main2.java:7)
Line 70 in LireFichierDecouper is "String part3 = line[2];"
PS:I'm very very new to java and eclipse, if you want me to post all the code to make it more clear I will.
If you work on eclipse, check "Problems" view for errors. Sometimes eclipse cannot compile code when your workspace has errors.
If you work on a running server, may be server do not recognize your changes. Restart it, may be this helps.
If double of above do not help you please explain exactly what you want and specify your development environment how it is.
A debugger would be helpful to see if you are reaching that code by adding a break point at the System.out.println. Also, where are you running the code? System.out.println would go where directed depending on how java is run. Please provide the command line if executing from the command line.

Adding a " to a string in code

I'm writing some code for web services for my Android app which uses JSON. The url should look like this
url = url + "?maddr=" + mailAddr + "&pwd=FB&lect=" + """ + lectName + """ + "&fb=Test";
This is because the Lectname may be two or more words. However the compiler wont accept """, is there a character I can precede the " with to get the compiler to accept it into my string?
Try " \" ". You have to escape the "
http://en.wikipedia.org/wiki/Escape_character
You need this in (nearly) every programming language.

writing a specific string to a file with Java

my codes dont seem to properly address what i intend to achieve.
a long string instead of a well broken and seperated string
it does not handle the 'seperator' appropriately ( produces , instead of ",")
also the 'optional' ( produces ' instead of " '")
Current result:
LOAD DATA INFILE 'max.csv'BADFILE 'max.bad'DISCARDFILE
'max.dis' APPEND INTO TABLEADDRESSfields terminated by,optionally enclosed
by'(ID,Name,sex)
the intended result should look like this
is there a better way of doing this or improving the above codes
Yeah. Use the character \n to start a new line in the file, and escape " characters as \". Also, you'll want to add a space after each variable.
content = " LOAD DATA\nINFILE "+ fileName + " BADFILE "+ badName + " DISCARDFILE " +
discardName + "\n\nAPPEND\nINTO TABLE "+ table + "\n fields terminated by \"" + separator
+ "\" optionally enclosed by '" + optional + "'\n (" + column + ")";
This is assuming fileName, badName, and discardName include the quotes around the names.
Don't reinvent the wheel... the apache commons-io library does all that in one line:
FileUtils.write(new File(controlName), content);
Here's the javadoc for FileUtils.write(File, CharSequence):
Writes a CharSequence to a file creating the file if it does not exist
To insert a new line you need to use \n or \r\n for windows
for example
discardName + "\n" //New line here
"APPEND INTO TABLE"
For the double quote symbol on the other hand you need to specifically type \" around the comma:
"fields terminated by \"" + separator +"\""
which will produce this ","
and that is similar to what the optional variable needs to be

\n won't work, not going to a new line

I'm creating a small program that saves a int value into a text file, saves it, and loads it when you start the program again. Now, I need 3 more booleans to be stored in the text file, I am writing things in the file with
public Formatter x;
x.format("%s", "" + m.getPoints() + "\n");
Whenever I want to go to a new line in my text file, with \n, it wont go to a new line, it will just write it directly behind the int value. I tried doing both
x.format("%s", "" + m.getPoints() + "\n");
x.format("%s", "" + m.getStoreItem1Bought() + "\n");
and
x.format("%s%s", "" + m.getPoints() + "\n", "" + m.getBought() + "\n");
but, both will just write the boolean directly behind the int value, without starting a new line. Any help on this?
I am using Windows 7 Ultimate 64 bits, and my text editor is Eclipse, I am running all of the code with Eclipse too.
More specifically, I would recommend using:
x.format("%d%n%s%n", m.getPoints(), m.getStoreItem1Bought());
Use this instead:
public static String newline = System.getProperty("line.separator");
Both of this options work. Your problem is in how you format the output:
System.out.format("%s" + newline + "%s" + newline, "test1", "test2");
System.out.format("%s%n%s", "test1", "test2");
Output:
test1
test2
test1
test2
Try using %n instead of \n when using format. For details on this, please see the Formatter API and search this page for "line separator" and you'll see.
No problem here:
System.out.format ("first: %s%s", "" + x + "\n", "" + y + "\n");
While I would prefere, to integrate the \n into the format String, not the values:
System.out.format ("second: %s\n%s\n", x, y);
Using Formatter.format works the same.
Well your syntax is surely quite.. interesting. Why use the formatting method if you're just piece the string together anyways? Also since you nowhere say what stream you're using we have to guess a bit, but anyways.
Anyways I'm betting that 1. you're using windows and 2. that the editor (I bet on notepad) you're using only reacts to \r\n since that's the correct newline for Windows. To fix this DON'T hardcode \r\n in your code but instead use %n and use the printf function correctly (ie don't piece the string together!).
Otherwise if you really have to piece the string together:
String newline = System.getProperty("line.separator");
x.format("%s", "" + m.getPoints() + newline);
will work.

Categories

Resources