这是一个家庭作业,我必须编写一个程序来读取“input.txt”文件并查看打印称呼的次数(例如:Donald Duck, 4 所以它打印 Hello Donald Duck 四次) m 是将称呼输出到一个名为“output.txt”的文本文件中,由于某种原因,它只打印出 input.txt 中最后一行的称呼,而不是全部。这是我到目前为止所拥有的:
import java.util.*;
import java.io.*;
public class Driver0 {
public static void main (String [] args) {
Scanner userInput = new Scanner(System.in);
System.out.println("Would you like the output to be written to a file?");
Scanner read;
String input = userInput.nextLine(); //user input
if(input.equals("yes")) {
System.out.println("Writing to \"output.txt\" now..");
}
else {
System.out.println("Printing to screen:");
}
try {
read = new Scanner(new File("input.txt")); //scanner reading file
}
catch (FileNotFoundException e){
System.out.println("File not found.");
return;
}
while(read.hasNextLine()) {
String newInput = read.nextLine();
String [] inputArray = newInput.split(","); //spliting
int num = 0;
num = Integer.parseInt(inputArray[2].trim());
for(int i = 0; i < num; i++) {
if(input.equals("yes")) { //writing to file
Driver0.outputting(inputArray);
}
else { //writing to screen
System.out.println("Hello" + inputArray[1] + inputArray[0]);
}
}
}
}
public static void outputting (String [] inputArray) {
PrintWriter output = null;
String fileName = "output.txt";
try {
output = new PrintWriter(new FileWriter(fileName));
}
catch(IOException error){
System.out.println("Sorry, can't open for writing.");
return;
}
output.println("Hello" + inputArray[1] + inputArray[0]);
output.close();
}
}
我的问题很可能在输出方法中,或者它有一条注释说写到它旁边的文件