从输入文件读取并使用Java写入输出文件

时间:2015-09-26 16:09:20

标签: java csv filereader filewriter

我目前正处于Java类的最后一周,我们的最终项目要求我们从输入CSV文件中的单个单元格中读取一个数字和运算符(用逗号分隔),让程序执行数学(从我选择的任何数字开始,然后让程序将结果写入输出CSV文件。我将代码转换为转换错误,但我确信这是我最不担心的。我对Java的理解我只是在课堂上失败了。我只是不认为我有编程的想法,我已经向教授表达了这一点。所以希望我能在这个最后的项目上做得很好,以提高我的成绩。说,我将立即远离这个学位计划。

-Mike

教授希望输出看起来像这样:

共添加2个

共添加6个

减去9总-1

总计10 -10

元素数量= 4,总数= -10,平均值= -2.5

这是错误: csvRead2.java:37:错误:不兼容的类型:int无法转换为String             number [i] =(Integer.parseInt(value [0])); //从String更改为整数。                                          ^

import java.io.*;

public class csvRead2 {
   public static void main(String args[]) {

      String operator[];
      String number[];
      String total;
      int i;

      // The name of the file to open.
      String inputFile = "mathInput.csv";

      // This will reference one line at a time
      String line = null;

      try { // start monitoring code for Exceptions
         // FileReader reads text files in the default encoding.
         FileReader read = new FileReader("mathInput.csv");
         // Always wrap FileReader in BufferedReader.
         BufferedReader buffRead = new BufferedReader(read);

         // Assume default encoding.
         FileWriter write = new FileWriter("mathOuput.csv", true); // true for append
         // Always wrap FileWriter in BufferedWriter.
         BufferedWriter buffWrite = new BufferedWriter(write);

         // The name of the file to open.
         String outputFile = "mathOutput.csv";

         while ((line = buffRead.readLine()) != null) {
            String[] value = line.split(",");
            operator[i] = value[1];
            number[i] = (Integer.parseInt(value[0])); // Change from a String to an integer.
            // Determine the operator and do the math operation and write to the output file.
            if (operator[i].equals("+")) { // if statement for addition operator
               total = total + number[i];
               buffWrite.write("Add  " + number[i] + "  total  " + total);
               buffWrite.newLine();
               if (operator[i].equals("-")) { // if statement for subtraction operator
                  total = total + number[i];
                  buffWrite.write("Subtract  " + number[i] + "  total  " + total);
                  buffWrite.newLine();
                  if (operator[i].equals("*")) { // if statement for multiplication operator
                     total = total + number[i];
                     buffWrite.write("Multiply  " + number[i] + "  total  " + total);
                     buffWrite.newLine();
                     if (operator[i].equals("/")) { // if statement for division operator
                        total = total + number[i];
                        buffWrite.write("Divide  " + number[i] + "  total  " + total);
                        buffWrite.newLine();
                        if (operator[i].equals("=")) { // if statement for equals operator
                           buffWrite.newLine();
                        }
                     }
                  }
               }
            }
         }
         // closing BufferedReader and BufferedWriter
         buffRead.close();
         buffWrite.close();
      }
      catch(FileNotFoundException ex) { // will catch if file is not found
         System.out.println( "Unable to open file '" + inputFile + "'");                                                
      }
      catch(IOException ex) // catches read and write errors
      {
         ex.printStackTrace(); // will print read or write error
      }
   }
}

3 个答案:

答案 0 :(得分:1)

  1. String number[]应为int number[]。如果要对整数进行操作,请将相应变量的数据类型更改为int。字符串不能用于添加数字。

  2. 即使修复了上述异常,也无法刷新写入操作。将数据写入文件需要buffWrite.flush()。在bufWrite上调用flush()之前,请致电close()

  3. 编辑:有很多逻辑错误,已经解决了。

    import java.io.*;
    
    public class CSVRead2 {
     public static void main(String args[]) {
    
      String operator[] = new String[1];
      int number[] = new int[1];
      int total = 0;
      int i=0;
    
      // The name of the file to open.
      String inputFile = "mathInput.csv";
    
      // This will reference one line at a time
      String line = null;
    
      try { // start monitoring code for Exceptions
         // FileReader reads text files in the default encoding.
         FileReader read = new FileReader("mathInput.csv");
         // Always wrap FileReader in BufferedReader.
         BufferedReader buffRead = new BufferedReader(read);
    
         // Assume default encoding.
         FileWriter write = new FileWriter("mathOuput.csv", true); // true for append
         // Always wrap FileWriter in BufferedWriter.
         BufferedWriter buffWrite = new BufferedWriter(write);
    
         // The name of the file to open.
         String outputFile = "mathOutput.csv";
    
         while ((line = buffRead.readLine()) != null) {
            String[] value = line.split(",");
            operator[i] = value[1];
            number[i] = (Integer.parseInt(value[0])); // Change from a String to an integer.
            // Determine the operator and do the math operation and write to the output file.
            if (operator[i].equals("+")) { // if statement for addition operator
               total = total + number[i];
               buffWrite.write("Add  " + number[i] + "  total  " + total);
               buffWrite.newLine();
            }else if (operator[i].equals("-")) { // if statement for subtraction operator
                  total = total - number[i];
                  buffWrite.write("Subtract  " + number[i] + "  total  " + total);
                  buffWrite.newLine();
            }
            else if (operator[i].equals("*")) { // if statement for multiplication operator
                     total = total + number[i];
                     buffWrite.write("Multiply  " + number[i] + "  total  " + total);
                     buffWrite.newLine();
            }
            else if (operator[i].equals("/")) { // if statement for division operator
                        total = total + number[i];
                        buffWrite.write("Divide  " + number[i] + "  total  " + total);
                        buffWrite.newLine();
            }
            else if (operator[i].equals("=")) { // if statement for equals operator
                           buffWrite.newLine();
            }
    
        }
        buffWrite.flush();   
        // closing BufferedReader and BufferedWriter
        buffRead.close();
        buffWrite.close();
      }
      catch(FileNotFoundException ex) { // will catch if file is not found
         System.out.println( "Unable to open file '" + inputFile + "'");                                                
      }
      catch(IOException ex) // catches read and write errors
      {
         ex.printStackTrace(); // will print read or write error
      }
    }
    }
    

    编辑2:

    mathinput.csv(文件中没有空行)

    2,+

    3,+

    9, -

    mathOutput.csv

    共添加2个

    共添加3

    减去9总计-4

答案 1 :(得分:0)

首先,将 number 数组的类型从 String [] 更改为 int [] 。您将整数存储到字符串数组中,因此是异常。

答案 2 :(得分:0)

valueString的数组,number也是String的数组。 现在你从value中取出一个字符串解析为一个整数并尝试再将它放入一个字符串数组中!

您可以将String number[]的类型更改为int number[]

你的变量总数也是如此!由于您在其中存储了Integer值,因此您应将其类型更改为int total

修改

此外,我注意到你正在链接if-blocks!我想你可能想再次考虑这个概念!如果您收到"-",则您的第一个if-block(if (operator[i].equals("+")))将导致false,并且该if-block中的所有代码都将不会被执行!