【问题标题】:Reading from an Input file and writing to an Output file in Java在 Java 中读取输入文件并写入输出文件
【发布时间】:2015-09-26 16:09:19
【问题描述】:

我目前正在上 Java 课程的最后一周,我们的期末项目要求我们让程序从输入 CSV 文件中的单个单元格中读取数字和运算符(用逗号分隔),让程序执行数学(从我选择的任何数字开始,然后让程序将结果写入输出 CSV 文件。我将代码归结为转换错误,但我确信这是我最不担心的。我对 Java 的理解是初级的,我的课程几乎不及格。我只是不认为我有编程的头脑,我已经向教授表达了这一点。所以希望我能在这个期末项目上做得足够好,以提高我的成绩。没必要也就是说,我要立即避开这个学位计划。

-迈克

这是教授希望输出的样子:

加2共2

加6共8

总共减去 9 个 -1

总共乘以 10 -10

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

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

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
      }
   }
}

【问题讨论】:

  • 您正试图将一个 int 放入一个字符串数组(数字)...

标签: java csv filereader filewriter


【解决方案1】:
  1. String number[] 应该是int number[]。如果您对整数进行操作,请将相应变量的数据类型更改为 int。字符串不能用于数字相加。

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

编辑:存在许多逻辑错误,已解决。

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共2

加 3 共 5

总共减去 9 -4

【讨论】:

  • 我能够运行并获得输出。按原样运行程序,无需任何更改
  • 记录了逻辑错误。感谢帮助!该程序正在编译,但是,我现在运行该程序时遇到问题。输入字符串“+”指的是我的 mathInput 文件中的第一个运算符。文件对我来说看起来不错,为什么它会给我这个错误?
    线程“主”java.lang.NumberFormatException 中的异常:对于输入字符串:java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) 处的“+”在 java.lang.Integer.parseInt(Integer.java :569) 在 java.lang.Integer.parseInt(Integer.java:615) 在 CSVRead3.main(CSVRead3.java:34) –
  • 在文件中按如下方式传递输入。第 1 行:2 + 第 2 行:3 + 第 3 行:9 -
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

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

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

    编辑:

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

    【讨论】:

    • 哦,我明白了,我想我不应该将它们嵌套在那里。只做后续的 if 语句对吗?
    • @Mike 或者你可以使用else if(...) 语句。但是,是的,后续的 if 语句会起作用!
    猜你喜欢
    • 2018-08-07
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-18
    • 2017-01-25
    相关资源
    最近更新 更多