这个项目的目标是创建一个食品日记。
这日记应该包含早餐,午餐,晚餐和小吃,你在白天吃。用户应该能够输入他们的食物项目,并将其保存为CSV文件。下面是到目前为止,当我将变量f和t写到excel时,它们在同一个单元格中的情况,如何使它们位于单独的列中?
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class App {
public static void main(String[] args) {
BufferedWriter bw = null;
FileWriter fw = null;
FileOutputStream FileName = new FileOutputStream( "MyFooDiary.csv");
System.out.println("Welcome to your food diary");
System.out.println("What is the name of your Food?");
Scanner x = new Scanner(System.in);
String f = x.nextLine();
System.out.println("Was this breakfast, lunch, dinner, or a snack");
Scanner y = new Scanner(System.in);
String t = y.nextLine();
try {
File file = new File(FileName);
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
// true = append file
fw = new FileWriter(file.getAbsoluteFile(), true);
bw = new BufferedWriter(fw);
bw.write("Date, Food Time, Food Name, Calories, Carbohydrates,
Sugars, Fiber, Protein, Total Fat ");
bw.write(t);
bw.write(f);;
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null)
bw.close();
if (fw != null)
fw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}}}
发布于 2017-05-03 05:22:05
您需要在值之间添加逗号,,才能使它们位于不同的单元格中。
尝试这个方法来检查t的结尾和f的开头是否没有",“。如果没有逗号,那么将逗号添加到t的末尾:
bw.write(t);
//check if the end of t and the start of f do not have a ",". If neither has a comma then add one to the end of t
if (t.endsWith(",") == false && f.startsWith(",") == false)
{
t = t + ",";
}
bw.write(f);我建议编写一个特殊的方法来对两个变量执行这样的检查,这样您就可以在任何地方调用它,我还注意到,在这行Sugars, Fiber, Protein, Total Fat ");的末尾缺少了一个",“。is应该有Fat, "); (注意逗号)。
https://stackoverflow.com/questions/43749991
复制相似问题