This is a homework assignment, I have to write a program that reads a “input.txt” file and sees how many times to print a salutation (ex: Donald Duck, 4 so it prints Hello Donald Duck four times)
The problem I’m having is with outputting the salutation into a text file called “output.txt”
For some reason it only prints out the salutation for the last line in the input.txt instead of all of them.. Here’s what I have so far:
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();
}
}
My problem is most likely within the outputting method or where it has a comment that says writing to file next to it
The
FileWriterclass has a second constructor that takes abooleanargument to tell it to append to the end of the existing file rather than overwrite it from the start.