将结果保存到csv中

时间:2017-11-23 15:15:57

标签: java

这是我的代码的副本, 我希望将以下代码的结果保存到csv中,并询问用户是否要查看结果?如果是,则显示已保存的csv的内容。

import java.io.*;

import java.util.Scanner;


public class TestMathOP {


    public static void main(String [] args) {

        float num1;

        float num2;


        Scanner input = new Scanner (System.in);

        char choice;

        do

        {

        System.out.print ("Enter the first number:");

        num1 = input.nextFloat();

               System.out.print ("Enter the second number:");

        num2 = input.nextFloat();

        System.out.println();

        System.out.println("The sum of the numbers is " + (num1 + num2)); 

        System.out.println("The subtract of the two numbers is " +  + (num1 - num2)); 

        System.out.print("Do you want to exit? Y/N ");

        choice = input.next().charAt(0);
        }

        while ((choice == 'n') || (choice == 'n'));

               System.out.print("Thanks for using our system");

        if ((choice == 'y') || (choice == 'y')); 

    }

}

1 个答案:

答案 0 :(得分:-1)

这应该有效。我想像@AlexZam说的那样,试着一步一步走。

public static void main(String[]args) throws IOException{
    //creates file
    File file = new File("file.csv");

    //Change to strings
    String num1;
    String num2;
    Scanner input = new Scanner (System.in);

    //your choice
    boolean isNo = false;
    boolean isYes = false;

    do

    {
        //enables writing to file
        FileWriter fileWriter = new FileWriter("file.csv");
        Scanner scanner = new Scanner(file);


        System.out.print ("Enter the first number:");

        float calc1;
        calc1 = input.nextFloat();
        String firstNumber = calc1 + "";
        //WRITES TO FILE
        fileWriter.write(firstNumber+"\n");

        System.out.print ("Enter the second number:");

        float calc2;
        calc2 = input.nextFloat();
        String secondNumber = calc2+"";

        //WRITES TO FILE
        fileWriter.write(secondNumber +"\n");

        String message = "The sum of the numbers is " + (calc1 + calc2) + "\nThe subtract of the two numbers is " + (calc1 - calc2);

        System.out.println(message);
        fileWriter.write(message);

        //close filewriting
        fileWriter.close();


        String question = ("Do you want to exit? Y/N ");
        System.out.print(question);
        String answer = input.next();

        if(answer.equals("y")) {
            isYes = true;
            while (scanner.hasNext()) {
                System.out.println(scanner.nextLine());
            }
        }else if(answer.equals("n")) {
            isNo = true;
            System.out.println("Thanks for using our systems!");
        }

    } while (!isNo&&!isYes);
}
相关问题