Problem with input/output code
Hello...
I am working on a simple code for class where Java asks how many songs do you want to input into your file, you put in the song, artist, and album of a song and Java will save it as a text file. I can get it to do that just fine, but if I enter in more than one set of data (another song, artist, album) it will not show.
So when I am asked to enter how many files I want to input, if I say 2 and then enter in:
I'll Stick Around/Foo Fighters/Foo Fighters
Above/Finger Eleven/Tip
The program will let me enter both items, but when I pull the file, only the Foo Fighters song will be on the file, the Finger Eleven song won't be.
How do I fix this? What am I doing wrong?
Here is the code...and thanks in advance for your help.
Code:
import java.util.Scanner;
import java.io.*;
public class PrescottFileDemo
{
public static void main(String[] args) throws IOException
{
String filename;
String songName;
String artistName;
String albumName;
int numSongs;
Scanner keyboard = new Scanner(System.in); //The scanner object for the keyboard
System.out.print("How many songs do you have? ");
numSongs = keyboard.nextInt();
keyboard.nextLine();
//Get the file name.
System.out.print("Enter the filename: ");
filename = keyboard.nextLine();
PrintWriter outputFile = new PrintWriter(filename);
//The Loop statement for how many songs you want to file.
for (int i = 1; i <= numSongs; i++)
{
System.out.print("Enter the name of a song " );
songName = keyboard.nextLine();
outputFile.println(songName);
System.out.print("Enter the artist ");
artistName = keyboard.nextLine();
outputFile.println(artistName);
System.out.print("Enter the album title ");
albumName = keyboard.nextLine();
outputFile.println(albumName);
//Closes the file when you're done.
outputFile.close();
System.out.println("Data written to the file");
}
}
}
Re: Problem with input/output code
It's quite simple really, you are closing the file inside the loop so by the time you move onto the second item to go into the file, the output file is closed. Move "outputFile.close()" outside of your for loop. Fixed :)
Re: Problem with input/output code
Awesome!! Thanks so much for your help on this...