[英]Writing to text file issue
public static void makeSandwich()
{
System.out.println("Enter First Name: ");
String name = Scanner.next();
double price = sandwich.getBreadPrice() + sandwich.getMeatPrice() + sandwich.getVegPrice();
sandwich.setPrice(price);
NumberFormat currency = NumberFormat.getCurrencyInstance();
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date) + " " + name + " " + sandwich.getBread() + " " + sandwich.getMeat() + " " + sandwich.getVegetables() + " " + currency.format(sandwich.getPrice()));
OrderLine.writeOrderLine(name, sandwich.getBread(), sandwich.getMeat(), sandwich.getVegetables(), sandwich.getPrice());
}
這是我的orderline.app代碼
public class OrderLine{
private static Sandwich sandwich = null;
public static void writeOrderLine(String name, String bread, String meat, String veg, double price)
{
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
try
{
File productsFile = new File("orderline.txt");
PrintWriter out = new PrintWriter(
new BufferedWriter(
new FileWriter(productsFile, true)));
out.print(dateFormat.format(date) + "\t");
out.print(name + "\t");
out.print(sandwich.getBread() + "\t");
out.print(sandwich.getMeat() + "\t");
out.print(sandwich.getVegetables() + "\t");
out.println(sandwich.getPrice() + "\t");
out.close();
}
catch (IOException e)
{
System.out.println(e);
}
}
}
它根本不會打印,但是當我在orderline.java中的dateformat之前添加“ sandwich = new Sandwich()”這一行時,它可以工作,但是由於我想創建一個新的三明治,最終卻給了我空字符串。 我怎么稱呼我已經做的三明治?
在writeOrderLine函數中,您尚未初始化三明治,但可以傳遞三明治的所有屬性,您可以按以下方式進行操作
public static void writeOrderLine(String name, String bread, String meat, String veg, double price)
{
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
try
{
File productsFile = new File("orderline.txt");
PrintWriter out = new PrintWriter(
new BufferedWriter(
new FileWriter(productsFile, true)));
out.print(dateFormat.format(date) + "\t");
out.print(name + "\t");
out.print(bread + "\t");
out.print(meat + "\t");
out.print(veg + "\t");
out.println(price+ "\t");
out.close();
}
catch (IOException e)
{
System.out.println(e);
}
}
或者你可以這樣
這樣叫
OrderLine.writeOrderLine(name, sandwich);
並將功能更改為
public static void writeOrderLine(String name, Sandwich sandwich)
{
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
try
{
File productsFile = new File("orderline.txt");
PrintWriter out = new PrintWriter(
new BufferedWriter(
new FileWriter(productsFile, true)));
out.print(dateFormat.format(date) + "\t");
out.print(name + "\t");
out.print(sandwich.getBread() + "\t");
out.print(sandwich.getMeat() + "\t");
out.print(sandwich.getVegetables() + "\t");
out.println(sandwich.getPrice() + "\t");
out.close();
}
catch (IOException e)
{
System.out.println(e);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.