【发布时间】: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