I want to write some data to a file and here is my code:
for (Season s : seasons) {
if (s.getYear() >= start && s.getYear() <= end) {
line += s.getYear() + ", " + s.getWinTeamName() + ", "
+ s.getMinorPremiersTeam() + ", "
+ s.getWoodenSpoonTeam()+ "\n"; }
}
System.out.println("File created.\n"); // Informing the user about
// the creation of the file.
out.write(line);
out.close();
My file is created but this is what I get:
2005, Wests Tigers, Parramatta, Newcastle2006, Broncos, Storm, Rabbitohs
But I want it to be:
2005, Wests Tigers, Parramatta, Newcastle
2006, Broncos, Storm, Rabbitohs
I thought the adding the "\n" at the end of the line variable would fix that but it hasn't.
Any suggestions on how to fix that?
You need to use the system-specific newline separator. See System.lineSeparator
If you use the java.io.BufferedWriter, the .newLine() method will insert the appropriate line separator.
for (Season s : seasons)
{
if (s.getYear() >= start && s.getYear() <= end)
{
String line = s.getYear() + ", " + s.getWinTeamName() + ", "
+ s.getMinorPremiersTeam() + ", "
+ s.getWoodenSpoonTeam();
out.write(line);
out.newLine();
}
}
for (Season s : seasons) {
if (s.getYear() >= start && s.getYear() <= end) {
line += s.getYear() + ", " + s.getWinTeamName() + ", "
+ s.getMinorPremiersTeam() + ", "
+ s.getWoodenSpoonTeam()+ "\r\n"; }
}
System.out.println("File created.\n"); // Informing the user about
// the creation of the file.
out.write(line);
out.close();
Related
Appreciate the help. I am using Java and I want to write a text in the file. I am not sure what is wrong with my code. Is below code sufficient since it is a snippets of the program? I am trying to write a text in the file and there is no error. When I tried opening the file, the file is blank.
PharmacyReceipt = is the file where the system will read it and compute the total price
PharmacyInvoice = if the money exceeds the total price, the system will write an invoice and delete the receipt file
Thank you
double change = 0;
grandTotal = 0;
try {
BufferedReader pharmacyFile = new BufferedReader(new FileReader("pharmacyReceipt.txt"));
BufferedWriter write1 = new BufferedWriter(new FileWriter("pharmacyInvoice.txt", true));
String input_1;
System.out.printf("%-16s %-50.30s %-20s %-20s %-20s\n", "Product Code", "Product Name", "Price", "Quantity", "Net Amount");
while ((input_1 = pharmacyFile.readLine()) != null) {
String[] data = input_1.split(",");
adminObject.setProductCode(data[0]);
adminObject.setName(data[1]);
adminObject.setPrice(Double.parseDouble(data[2]));
adminObject.setQuantity(Double.parseDouble(data[3]));
adminObject.setTax(Double.parseDouble(data[4]));
adminObject.setDiscount(Double.parseDouble(data[5]));
int MAX_CHAR = 40;
int maxLength = (adminObject.getName().length() < MAX_CHAR) ? adminObject.getName().length() : MAX_CHAR;
//grossAmount = adminObject.getPrice() * (adminObject.getTax()/100);
//netAmount = adminObject.getQuantity() * (grossAmount - (grossAmount * adminObject.getDiscount()/100));
netAmount = adminObject.getPrice() * adminObject.getQuantity();
System.out.printf("%-16s %-50.30s %-20.2f %-20.2f %.2f\n", adminObject.getProductCode(), adminObject.getName().substring(0, maxLength), adminObject.getPrice(), adminObject.getQuantity(), netAmount);
//System.out.println(adminObject.getProductCode() + "\t \t " + adminObject.getName() + "\t\t " + adminObject.getPrice() + "\t\t " + adminObject.getQuantity() + "\t\t " + adminObject.getTax() + "\t " + adminObject.getDiscount());
grandTotal += netAmount;
}
System.out.printf("\nGrand Total = PHP %.2f\n\n", grandTotal);
pharmacyFile.close();
System.out.print("Do you want to proceed to print the receipt? ");
choice_3 = sc.nextLine();
choice_3 = choice_3.toUpperCase();
if (choice_3.equals("YES") || choice_3.equals("Y")) {
System.out.print("\nHow much is the money? ");
double money = sc.nextDouble();
if (grandTotal <= money) {
BufferedReader groceryFile1 = new BufferedReader(new FileReader("pharmacyReceipt.txt"));
System.out.printf("%-16s %-50.30s %-20s %-15s %-20s\n", "Product Code", "Product Name", "Price", "Quantity", "Net Amount");
while ((input_1 = groceryFile1.readLine()) != null) {
String[] data = input_1.split(",");
adminObject.setProductCode(data[0]);
adminObject.setName(data[1]);
adminObject.setPrice(Double.parseDouble(data[2]));
adminObject.setQuantity(Double.parseDouble(data[3]));
adminObject.setTax(Double.parseDouble(data[4]));
adminObject.setDiscount(Double.parseDouble(data[5]));
int MAX_CHAR = 40;
int maxLength = (adminObject.getName().length() < MAX_CHAR) ? adminObject.getName().length() : MAX_CHAR;
//grossAmount = adminObject.getPrice() * (adminObject.getTax()/100);
//netAmount = adminObject.getQuantity() * (grossAmount - (grossAmount * adminObject.getDiscount()/100));
netAmount = adminObject.getPrice() * adminObject.getQuantity();
write1.write(adminObject.getProductCode() + "," + adminObject.getName() + "," + adminObject.getPrice() + "," + adminObject.getQuantity() + "," + adminObject.getTax() + "," + adminObject.getDiscount() + "," + adminObject.getTax() + "," + adminObject.getDiscount() + "\n");
System.out.printf("%-16s %-50.30s %.2f\t\t %.2f\t\t %.2f\n", adminObject.getProductCode(), adminObject.getName().substring(0, maxLength), adminObject.getPrice(), adminObject.getQuantity(), netAmount);
//System.out.println(adminObject.getProductCode() + "\t \t " + adminObject.getName() + "\t\t " + adminObject.getPrice() + "\t\t " + adminObject.getQuantity() + "\t\t " + adminObject.getTax() + "\t " + adminObject.getDiscount());
}
write1.write("___________________________________________________");
write1.write("\nGrand Total = PHP %.2f\n\n" + grandTotal);
write1.write("Money: " + money + "\n");
write1.write("Change: " + (change = money - grandTotal) + "\n");
write1.write("___________________________________________________\n");
System.out.println("___________________________________________________\n");
System.out.printf("\nGrand Total = PHP %.2f\n\n", grandTotal);
System.out.println("Money: " + money + "\n");
System.out.println("Change: " + (change = money - grandTotal) + "\n");
System.out.println("___________________________________________________\n");
}
} else {
System.out.println("___________________________________________________\n");
System.out.println("***Money exceeds the amount.***");
System.out.println("___________________________________________________\n");
}
pharmacyFile.close();
} catch (FileNotFoundException e) {
System.out.println("File Not Found" + e);
} catch (IOException e) {
System.out.println("File Not Found");
} catch (NumberFormatException e) {
System.out.println(e);
} catch (Exception e) {
System.out.println(e);
}
break;
You have to close the writer at the end via writer1.close(). Because you have a BufferedWriter, it is not writing to the file always immediately. If then your program for example exits before it can write, your content to the file, it will remain blank.
Also you should just in general always close this kind of resources at the end as they might cause memory leaks and other problems. You can do it via:
try (FileWriter writer1 = new FileWriter(new File("blablub")) {
// ... do your stuff with the writer
}
This is called a try-with-resources clause and will close the Resource in the end automatically. The more explicit version is:
FileWriter writer1 = new FileWriter(newFile("blablub"));
try {
// ... do your stuff with the writer
} catch (Exception ex) {
...
} finally {
writer1.close();
}
Edit: It might be, that you are thinking that you are closing the writer1 as I've now seen, but actually you have two calls to pharmacyFile.close(). Maybe this is your issue.
The line with the problem is. This line should check if the 3rd index contains character and it should not contain the words north and america.
else if ( salida[3].matches("[a-zA-Z]+") && !salida[3].equals("North") ) { // not working correctly
if ( !salida[3].equals("America")) {
salida1 = salida1 + salida[0] + " " + salida[1] + " " + salida[2] + " " + salida[3] + ",";
The code above should run for the 4th line of the array data below
[United, States, 1,527,664, 90,978, North, America]
[Canada, 77,002, 5,782, North, America]
[Turks, and, Caicos, 12, 1, North, America]
[St., Vincent, &, Grenadines, 17, 0, North, America]
this is the string output I'm currently getting which doesn't add the 3rd index of the array to the string
United States,Canada ,Mexico ,Dominican Republic,Panama ,Honduras ,Guatemala ,Cuba ,El Salvador,Costa Rica,Jamaica ,Haiti ,Martinique ,Guadeloupe ,Bermuda ,Trinidad and,Aruba ,Bahamas ,Cayman Islands,Barbados ,Sint Maarten,Saint Martin,Nicaragua ,Antigua and,Grenada ,Belize ,Saint Lucia,St. Vincent,CuraƧao ,Dominica ,Saint Kitts,Turks and,Montserrat ,Greenland ,British Virgin,Saint Barthelemy,Caribbean Netherlands,Anguilla ,Saint Pierre,
Input country to display data:
This is my entire code
public String setCountriesList() {
String salida1 = "";
try {
Document doc = Jsoup.connect("https://www.worldometers.info/coronavirus/countries-where-coronavirus-has-spread/").get();
Elements tr = doc.select("tr");
String [] na = {"north", "america"};
for (int i = 0; i < tr.size(); i++) {
if (tr.get(i).text().contains("North America")) {
String[] salida = tr.get(i).text().split(" ");
System.out.println(salida[3].contains("North") + " and " + salida[3].contains("America") );
System.out.println(Arrays.deepToString(salida)); //split salida to country, number ,number in array
if ( salida[1].matches("[a-zA-Z]+")) {
salida1 = salida1 + salida[0] + " " + salida[1] + ",";
}
else if ( salida[2].matches("[a-zA-Z]+")) {
salida1 = salida1 + salida[0] + " " + salida[1] + " " + salida[2] + ",";
}
else if ( salida[3].matches("[a-zA-Z]+") && !salida[3].equals("North") ) { // not working correctly
if ( !salida[3].equals("America")) {
salida1 = salida1 + salida[0] + " " + salida[1] + " " + salida[2] + " " + salida[3] + ",";
}}
```
else {
salida1 = salida1 + salida[0] + " ,";
}
}
}
return salida1;
} catch (Exception ex) {
System.out.println("error");
return "error";
}
}
The issue is that the names of the countries contain a comma "," which is your separator character. You need to find a way to have the country name within the same index 0, or at least wrap the country name in quotes "", so that "North" is effectively index 3. In the examples above "North" was only index 3 for Canada.
So I've tried pretty much everything to get rid of the last newline character in my code. Its supposed to print a new line after every recursive call except for the last one. Any ideas?
public static boolean solve(double target, ArrayList<Double> numbers)
{
String print = "";
String newPrint = "";
double compare = 0;
boolean done = false;
for (double num : numbers)
{
if (!done)
{
ArrayList<Double> remaining = new ArrayList<Double>(numbers);
remaining.remove(num);
if (target == num)
{
done = true;
}
else
{
done = solve(target + num, remaining);
if (done)
{
print += ((int) target + (int) num) + " " + "-" + " " + (int) num + " "
+ "="
+ " "
+ ((int) target + "\n");
}
else
{
done = solve(target - num, remaining);
if (done)
{
print += ((int) target - (int) num) + " " + "+" + " " + (int) num + " "
+ "=" + " "
+ ((int) target + "\n");
}
else
{
done = solve(target * num, remaining);
if (done)
{
print += ((int) target * (int) num) + " " + "/" + " " + (int) num
+ " " + "=" + " "
+ ((int) target + "\n");
}
else
{
done = solve(target / num, remaining);
if (done)
{
print += ((int) target / (int) num) + " " + "*" + " "
+ (int) num
+ " " + "="
+ " " + ((int) target + "\n");
}
}
}
}
}
}
}
System.out.print(print);
return done;
}
}
For instance:
void recursiveF(...) {
if ... {
recursiveF(...);
println();
}
...
}
The result is a string but you don't want the last character, so remove it:
print = print.substring(0, print.length()-1);
Use trim() method. It will remove white spaces, newline etc from beginning and end of string.
System.out.print(print.trim());
Short Print the new line character before.
The first thing the recursive function should do is print the new line character.
This way you shift the odd case from the last function call, to the first call, which should not prepend a new line character.
You could add a parameter String prepend = "" to the signature of the recursive method, it's empty on the first call, all further calls have it set to String prepend = "\n".
Then you can just print prepend without bothering with its content.
I've been trying to write a method in java to write data from an array to a text file but I'm getting two errors.
public void WriteStudentDetailsToFile() {
PrintWriter out = null;
try {
out = new PrintWriter("StudentDetails.txt");
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage());
System.out.println("in " + System.getProperty("user.dir"));
System.exit(1);
}
for (int i = 0; i < enrolment.length; i += 1) {
if (enrolment[i] != null) {
Student a = this.enrolment[i];
if (a.getName().equals("") || a.getAddress().equals("") || a.getDOB().equals("") || a.getGender().equals("")) {
break;
} else {
String record = a.getName() + "\t" + "0" + "\t" + a.getAddress() + "\t" a.getDOB() + "\t" + a.getGender();
out.println(record);
}
}
}
}
}
The two errors are
C:\Users\B00661059\Downloads\Assignment 2\Assignment 2\Student_Enrolment.java:137: error: ';' expected
String record = a.getName() + "\t" + "0" + "\t" + a.getAddress() + "\t" a.getDOB() + "\t" + a.getGender();
^
C:\Users\B00661059\Downloads\Assignment 2\Assignment 2\Student_Enrolment.java:137: error: not a statement
String record = a.getName() + "\t" + "0" + "\t" + a.getAddress() + "\t" a.getDOB() + "\t" + a.getGender();
On line 137, you need to add a concatenation operator (+) here:
"\t" + a.getDOB()
The most obvious error is that you are missing a plus here: + "\t" a.getDOB() +.
It should be
String record = a.getName() + "\t" + "0" + "\t" + a.getAddress() + "\t" + a.getDOB() + "\t" + a.getGender();
You might also want to look into how to define and use a toString() function in your Student class to control the string representation of the object.
Try this :
String record = a.getName() + "\t" + "0" + "\t" + a.getAddress() + "\t" + a.getDOB() + "\t" + a.getGender();
instead of this :
String record = a.getName() + "\t" + "0" + "\t" + a.getAddress() + "\t" a.getDOB() + "\t" + a.getGender();
Also this doesn't make sense :
if (a.getName().equals("") || a.getAddress().equals("") || a.getDOB().equals("") || a.getGender().equals("")) {
break;
}
Since you are only interested in the else branch you can negate it.
if !(a.getName().equals("") || a.getAddress().equals("") || a.getDOB().equals("") || a.getGender().equals("")) {
// Do what you want
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have read several posts suggesting to clear a JLabel (displayEntered) on a panel (display) with text by using the setText(" "). However, I have tried this and the outcome is it is just posting the array entered twice and does not clear the first set. I have an action shown below when a button is pressed both times; the first is to enter the data entered (I have the same code 4 times for the 4 different possible objects to enter but just put in the one since it's basically the same), which works fine and the second is to remove a specific one shown. My code is long, so am just putting that in. If someone wants something else please let me know. Thanks, I'd appreciate any input!
//adds the Herb data to the Array and list
enterHerbData.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
if(e.getActionCommand().equals("Enter")){
Name = NameTxt.getText();
Colors = ColorTxt.getText();
ID = (int) IDCmbo.getSelectedItem();
Flavor = FlavorTxt.getText();
if(((String) MedicinalCmbo.getSelectedItem()).equals("Yes"))
Medicinal = true;
else
Medicinal = false;
if(((String) SeasonalCmbo.getSelectedItem()).equals("Yes"))
Seasonal = true;
else
Seasonal = false;
plants[count] = new Herb(Name, ID, Colors, Flavor, Medicinal, Seasonal);
String displayArraytemp = " ";
if(plants[count] != null){
if(plants[count] instanceof Flower){
displayArraytemp = ((count + 1) + ": " + plants[count].getID() + ", " + plants[count].getName() + ", " + ((Flower)plants[count]).getColor() + ", " + ((Flower)plants[count]).getSmell() + ", Thorny: " + ((Flower)plants[count]).getThorns() + "\n");
}
else if(plants[count] instanceof Fungus){
displayArraytemp = ((count + 1) + ": " + plants[count].getID() + ", " + plants[count].getName() + ", " + ((Fungus)plants[count]).getColor() + ", Poisonous: " + ((Fungus)plants[count]).getPoisonous() + "\n");
}
else if(plants[count] instanceof Weed){
displayArraytemp = ((count + 1) + ": " + plants[count].getID() + ", " + plants[count].getName() + ", " + ((Weed)plants[count]).getColor() + ", Edible: " + ((Weed)plants[count]).getEdible() + ", Medicinal: " + ((Weed)plants[count]).getMedicinal() + ", Poisonous: " + ((Weed)plants[count]).getPoisonous() + "\n");
}
else if(plants[count] instanceof Herb){
displayArraytemp = ((count + 1) + ": " + plants[count].getID() + ", " + plants[count].getName() + ", " + ((Herb)plants[count]).getColor() + ", " + ((Herb)plants[count]).getFlavor() + ", Medicinal: " + ((Herb)plants[count]).getMedicinal() + ", Poisonous: " + ((Herb)plants[count]).getSeasonal() + "\n");
}
sb.append("<html>" + displayArraytemp).
append("<br> ");
displayArray = sb.toString();
}
displayEntered.setText(displayArray);
count++;
frameB.setVisible(false);
}
}
});
//removes the data to the Array and panel
ActionListener RemoveAction = new ActionListener(){
#Override
public void actionPerformed(ActionEvent RemoveAction){
if(RemoveAction.getActionCommand().equals("Enter")){
if((Btn1).isSelected()){
String displayArraytemp2 = " ";
if(count >= 1){
for(int n = 0; n < count; n++){
plants[n] = plants[n+1];
}
count--;
frameB.setVisible(false);
displayEntered.setOpaque(true);
for(int n = 0; n < 25; n++){
if(plants[n] != null){
if(plants[n] instanceof Flower){
displayArraytemp2 = ((n + 1) + ": " + plants[n].getID() + ", " + plants[n].getName() + ", " + ((Flower)plants[n]).getColor() + ", " + ((Flower)plants[n]).getSmell() + ", Thorny: " + ((Flower)plants[n]).getThorns() + "\n");
}
else if(plants[n] instanceof Fungus){
displayArraytemp2 = ((n + 1) + ": " + plants[n].getID() + ", " + plants[n].getName() + ", " + ((Fungus)plants[n]).getColor() + ", Poisonous: " + ((Fungus)plants[n]).getPoisonous() + "\n");
}
else if(plants[n] instanceof Weed){
displayArraytemp2 = ((n + 1) + ": " + plants[n].getID() + ", " + plants[n].getName() + ", " + ((Weed)plants[n]).getColor() + ", Edible: " + ((Weed)plants[n]).getEdible() + ", Medicinal: " + ((Weed)plants[n]).getMedicinal() + ", Poisonous: " + ((Weed)plants[n]).getPoisonous() + "\n");
}
else if(plants[n] instanceof Herb){
displayArraytemp2 = ((n + 1) + ": " + plants[n].getID() + ", " + plants[n].getName() + ", " + ((Herb)plants[n]).getColor() + ", " + ((Herb)plants[n]).getFlavor() + ", Medicinal: " + ((Herb)plants[n]).getMedicinal() + ", Poisonous: " + ((Herb)plants[n]).getSeasonal() + "\n");
}
sb.append("<html>" + displayArraytemp2).
append("<br> ");
displayArray = sb.toString();
}
}
}
displayEntered.setText(" ");
displayEntered.setText(displayArray);
}
}
}};
Your real problem is that you are re-using sb without clearing it.