首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我无法理解如何将用户的输入输入到不同的excel列中。

我无法理解如何将用户的输入输入到不同的excel列中。
EN

Stack Overflow用户
提问于 2017-05-03 02:15:51
回答 1查看 63关注 0票数 0

这个项目的目标是创建一个食品日记。

这日记应该包含早餐,午餐,晚餐和小吃,你在白天吃。用户应该能够输入他们的食物项目,并将其保存为CSV文件。下面是到目前为止,当我将变量f和t写到excel时,它们在同一个单元格中的情况,如何使它们位于单独的列中?

代码语言:javascript
复制
    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();

        }
    }

}}

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-05-03 05:22:05

您需要在值之间添加逗号,,才能使它们位于不同的单元格中。

尝试这个方法来检查t的结尾和f的开头是否没有",“。如果没有逗号,那么将逗号添加到t的末尾:

代码语言:javascript
复制
    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, "); (注意逗号)。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43749991

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档