我目前處於Java類的最後一週,我們的最終項目需要我們讓程序讀取數字和運算符(用逗號分隔)輸入CSV文件中的單個單元格,讓程序執行數學運算(從我選擇的任意數字開始,然後讓程序將結果寫入輸出CSV文件。我將代碼縮減爲轉換錯誤,但我是我對Java的理解是最基本的,而且我幾乎失敗了,我只是覺得我沒有編程思想,並且已經向教授表達了,所以希望我能做到這個最後的項目已經足夠讓我的成績升級了,不用說,我馬上就會避開這個學位計劃。-Mike從輸入文件中讀取數據並寫入Java文件中的輸出文件
這是想要的東西教授輸出看起來像:
添加2共2
添加6共8
減去9總-1
乘10總數-10
元素數量= 4,總數= -10,平均值= -2.0
這是錯誤: csvRead2.java:37:錯誤:不兼容的類型:int不能轉換爲字符串 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中的字符串(數字)數組... –