Java食品日记

时间:2018-04-18 17:40:13

标签: java java.util.scanner

这个项目的目标是制作食物日记。这本日记应包含您在白天消费的早餐,午餐,晚餐和小吃。用户应该能够输入他们的食物并将其保存为csv文件。用户应该能够继续追加文件。

这是我到目前为止所做的,但我不知道在哪里关闭我的扫描仪:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;

public class App {

    public static void main(String[] args) throws FileNotFoundException {

        PrintWriter pw = new PrintWriter(new File("test.csv"));
        StringBuilder sb = new StringBuilder();
        sb.append("Date");
        sb.append(',');
        sb.append("FoodTime");
        sb.append(',');
        sb.append("FoodItem");
        sb.append(',');
        sb.append("Calories");
        sb.append('\n');


        int exit;
        do {
            Scanner sc = new Scanner(System.in);
            System.out.println("Date : ");
            String Date = sc.next();
            System.out.println("Meal Time: ");
            String FoodTime = sc.next();
            System.out.println("Food Item : ");
            String FoodItem = sc.next();
            System.out.println("Calories : ");
            String Calories = sc.next();
            sb.append(Date);
            sb.append(',');
            sb.append(FoodTime);
            sb.append(',');
            sb.append(FoodItem);
            sb.append(',');
            sb.append(Calories);
            sb.append('\n');
            pw.write(sb.toString());
            System.out.println("Please enter 0 to exit, 1 to continue : ");
            exit = sc.nextInt();
        } while (exit != 0);


        System.out.println("done!");
    }

}

3 个答案:

答案 0 :(得分:0)

You should create the Scanner Object Before the do loop because at every iteration a new object is being created and you should close the Scanner Object after the end of do loop.

答案 1 :(得分:0)

You are creating a new scanner on every interaction inside your do while. Try to create a new scanner before the loop and close it after.

Scanner sc = new Scanner(System.in);
do {
        System.out.println("Date : ");
        String Date = sc.next();
        System.out.println("Meal Time: ");
        String FoodTime = sc.next();
        System.out.println("Food Item : ");
        String FoodItem = sc.next();
        System.out.println("Calories : ");
        String Calories = sc.next();
        sb.append(Date);
        sb.append(',');
        sb.append(FoodTime);
        sb.append(',');
        sb.append(FoodItem);
        sb.append(',');
        sb.append(Calories);
        sb.append('\n');
        pw.write(sb.toString());
        System.out.println("Please enter 0 to exit, 1 to continue : ");
        exit = sc.nextInt();
    } while (exit != 0);
sc.close();

答案 2 :(得分:0)

I'm not sure where to close my scanner:

To answer your question, you need to close it right before the last line:

pw.close();
sc.close();
System.out.println("done!");

You need to also declare the Scanner outside of the do loop:

int exit;
Scanner sc = new Scanner(System.in);
do {