Results 1 to 10 of 10
  1. #1
    Join Date
    Apr 2008
    Posts
    7
    Rep Power
    0

    Default [SOLVED] Writing ArrayList to Text File on seperate Lines

    Well, I'm making this app, and I need to get my ArrayList to print into a text file. The problem is that after I run the program I go to check my file I find that courseOutput is on the first line, along with the the first line from ArrayList list234, or actually, printArray. Can some one help me out i've been here for an hour and I can't get this to move any further. I need to have each item appear on a seperate line, and so far it seems as though online one line is being written to the ArrayList or text file.

    Java Code:
    public static void main(String args[])
        {
            // display a welcome message
            System.out.println("Welcome to the Gradebook Application");
            System.out.println();
    
            Scanner sc = new Scanner(System.in);
            String addClassChoice = "";
    		do
    		{
    			//Initialize course variables
    			int numberOfStudents = 0;
    			double highestGrade = 0.0;
    			double lowestGrade = 100.0;
    			double averageGrade = 0.0;
    			double totalGrades = 0.0;
    						
    			// Get and create a course
    			Course course = new Course();
    			course.setCourseArray(Validator.getArrayList());	
    			ArrayList<String> courseArray = course.getCourseArray();
    			//Create Text Output File
    			String fileDir = "c:/";
    			String outputName = "courseOutput.txt";
    			File  courseOutput = new File(fileDir + outputName);
    			
    			
    			//Ask Which Course to Add Students For			
    			int whichCourse = Validator.getInt(sc, "What course would you like to add a student for," +
    					" CIS 234, 235, or 311?\n" +
    					"(Enter the course number eg: \"235\" or \"999\" to exit)");
    			
    			PrintWriter out = null;
    			ArrayList<String> list234 = new ArrayList<String>();
    			
    			if (whichCourse == 234){
    				
    				try{
    					out = new PrintWriter(
    									  new BufferedWriter(
    									  new FileWriter(courseOutput)), true);
    				
    				//Add course to file
    				out.write(courseArray.get(0));
    								
    				//Check if the user wants to enter a student
    	       		String addStudentChoice = Validator.getStringYesNoAnswer(sc,"Would you like to add a student" +
    	       				"to CIS234?: ");
    				while (addStudentChoice.equalsIgnoreCase("y"))
    				{
    					System.out.println();
    	
    					//Get and create a student
    					UndergraduateStudent undergraduateStudent = new UndergraduateStudent();
    	
    					undergraduateStudent.setName(Validator.getStringWithinRange(sc,"What is the student's name?: ",1,100));
    					undergraduateStudent.setGrade(Validator.getDoubleWithinRange(sc,"What is the student's grade?: ",0.0,100.0));
    	
    					System.out.println("The student named '" + undergraduateStudent.getName() + "' earned the grade: " + undergraduateStudent.getLetterGrade());
    					System.out.println();
    	
    					//Perform student calculations
    					numberOfStudents += 1;
    					highestGrade = Math.max(highestGrade,undergraduateStudent.getGrade());
    					lowestGrade = Math.min(lowestGrade,undergraduateStudent.getGrade());
    					totalGrades += undergraduateStudent.getGrade();
    					
    					
    					list234.add(Student.getCount()
    							+ "\t" + undergraduateStudent.getName()
    							+ "\t" + undergraduateStudent.getLetterGrade()
    							+ "\t" + undergraduateStudent.getGrade());
    					
    					
    					addStudentChoice = Validator.getStringYesNoAnswer(sc,"Would you like to add a student?: ");
    				}
    	
    				//Perform course calculations
    				averageGrade = totalGrades/numberOfStudents;	
    				
    				}catch(Exception IO){
    					
    				}finally{
    					String printArray = "";
    					   for (Object object :  list234){
    					      printArray += object + "\n";
    					
    
    					out.write(printArray);
    					out.close();
    					}
    				}
    				
    			}else if(whichCourse == 999){
    				System.exit(0);				
    			}

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,585
    Rep Power
    23

    Default

    e I find that courseOutput is on the first line, along with the the first line from ArrayList list234, or actually, printArray.
    Not sure what this means. Can you copy a small section of the output file and add comments to it to describe what is wrong and what you want to change about it?

    To put output to separate lines put a lineend character (\n) where you want the one line to end. Or use a println() method which will also put a lineend character out at the end of what it is printing.

  3. #3
    Join Date
    Apr 2008
    Posts
    7
    Rep Power
    0

    Default

    OK, well, my first output to my text file is from courseArray (not courseOutput, sorry) which is read from another .txt file, it prints correctly.

    Java Code:
    try{
         out = new PrintWriter(
    	      new BufferedWrite
                  new FileWriter(courseOutput)), true);
    				
    	//Add course to file
    	out.write(courseArray.get(0));
    Then I let the user input student data, and store it in ArrayList list234 with tabs seperating student number, name, letter grade, and numerical grade

    Java Code:
    list234.add(Student.getCount()
         + "\t" + undergraduateStudent.getName()
         + "\t" + undergraduateStudent.getLetterGrade()
         + "\t" + undergraduateStudent.getGrade());
    Later, at the end of my try statement, I use the following code in order to turn the data in the ArrayList into a string with "\n" to make new lines for each item in the list.

    Java Code:
    finally{
    	String printArray = "";
    	     for (Object object :  list234){
    	          printArray += object + "\n";
    	          out.write(printArray);
                      out.close();
    	}
    I've tested this by entering the data for three students, but my outputs appear in one line:
    CIS 234 Java Programming1 john C 78.0

    instead of appearing the way I need it:
    CIS 234 Java Programming
    1 John C 78.0
    2 Jane A 97.0
    3 Joe B 87.5
    Attached Files Attached Files

  4. #4
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,585
    Rep Power
    23

    Default

    In the for loop you show, what are the values of object?
    Add a println("object=" + object);
    to show each of the values that are being appended to printArray

    The use of \t will only have an effect if the program that sees the \t does tabbing. Does the program/method you are using to output that data do tabbing? Otherwise its just the same as a space.

  5. #5
    Join Date
    Apr 2008
    Posts
    7
    Rep Power
    0

    Default

    if i add two students via input i got:
    object=1 john B 87.0
    object=2 jane A 94.0

    so object is printing the correct data, so
    printArray += object + "\n"; seems to be the culprit?

    tabbing works, the single line that is written to the text file has the tabs on it.

  6. #6
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,585
    Rep Power
    23

    Default

    drop the += and code it explicity:
    x = x + y + z vs x += y + z

  7. #7
    Join Date
    Apr 2008
    Posts
    7
    Rep Power
    0

    Default

    After coding it explicitly i seem to get the same result:

    CIS 234 Java Programming1 John C 78.0


    and if i move out.close(); out of the try statement:
    Java Code:
    }finally{
    	String printArray = "";
    		   for (String element :  list234){
    		      printArray += object + "\n";
    					
    
    		out.write(printArray);
    		//out.close();
    		}
    	}
    	out.close			
            }else if(whichCourse == 999){
    		System.exit(0);
            }

    CIS 234 Java Programming1 John C 78.01 John C 78.02 Jane A 97.01 John C 78.02 Jane A 97.03 Joe B 87.5

    which, if it added newline lines correctly, i assume would look like this:
    CIS 234 Java Programming
    1 John C 78.0
    1 John C 78.0
    2 Jane A 97.0
    1 John C 78.0
    2 Jane A 97.0
    3 Joe B 87.5

    i've also changed Object object, to String element.

    is there any other information i can give you? i'm feeling a bit stumped

    A good way to phrase my question would be "How would I make an ArrayList, a String, with each item delimited by a new line"
    Last edited by shinjitsunohana; 08-27-2008 at 03:36 AM.

  8. #8
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,585
    Rep Power
    23

    Default

    I don't see the println() statement in the code you posted. Where did you put it?
    As you get each element from the ArrayList do a println() to show what you get. then append it to the printArrayVariable.
    If you build a String by concatenating strings and \n and then print it, you should see some results.
    It must be the code you are posting is not what you are executing. Otherwise I can't explain why the \n is not causing a new line.

    Write a small program that builds a string with \n and prints it to see how to build a string and print it with newlines.

  9. #9
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    8

    Default

    You seem to be having trouble with newLines in your output. There are too many missing classes in your code to deal with. So I made up a small, exploratory app to help zero–in on the trouble.
    The main problem seems to be the way you were writing the list strings to file. PrintWriter has a println method you could try.
    Java Code:
    import java.io.*;
    import java.util.*;
    
    public class OutTest {
        public static void main(String[] args) {
            // Some data to load into a list.
            String[] names =        { "Mary", "Bill", "Sue", "John" };
            String[] letterGrades = { "A",    "B",    "C",   "B"    };
            double[] grades =       {  96.2,   88.7,   73.4,  85.2  };
            List<String> list = new ArrayList<String>();
    
            // Add data to list, one line at a time.
            for(int i = 0; i < names.length; i++) {
                String line = String.valueOf(i) + " " +
                              names[i]          + " " +
                              letterGrades[i]   + " " +
                              grades[i];
                list.add(line);
            }
            // Check output.
            writeToFile(list, "outTest1.txt");
    
            // Empty list and reuse.
            list.clear();
    
            // Add data to list again, using tabs.
            for(int i = 0; i < names.length; i++) {
                list.add(String.valueOf(i)
                    + "\t" + names[i]
                    + "\t" + letterGrades[i]
                    + "\t" + grades[i]);
            }
            // Check output.
            writeToFile(list, "outTest2.txt");
        }
    
        private static void writeToFile(List<String> list, String path) {
            System.out.println("writing to " + path);
            BufferedWriter out = null;
            try {
                File file = new File(path);
                out = new BufferedWriter(
                      new FileWriter(file));
                for (String s : list) {
                    // Print each line to console.
                    System.out.println(s);
                    // Write line to file.
                    out.write(s);
                    // Write newLine with BufferedReader method.
                    out.newLine();
                }
                out.close();
            } catch(IOException e) {
                System.out.println("IO error for " + path +
                                   ": " + e.getMessage());
            }
        }
    }

  10. #10
    Join Date
    Apr 2008
    Posts
    7
    Rep Power
    0

    Default

    Yeah, last night I solved the great mystery, it was right under my nose the whole time. Thanks for everyone's posts though, I finally just changed the code to:

    Java Code:
    }finally{
    					
    	//Add summary totals to end of ArrayList
    	outputList.add("\n");
    	outputList.add("Highest grade:      " + deci.format(highestGrade));
    	outputList.add("Lowest grade:       " + deci.format(lowestGrade));
    	outputList.add("Average grade:      " + deci.format(averageGrade));
    	outputList.add("Average letter:     " + Student.determineLetterGrade(averageGrade));
    					
    	//Write ArrayList to File
    	for (String printArray  :  outputList){						   						
    	out.println(printArray);
    					
    			}
    		}				
    	//Flush Data
    	out.close();
    Thanks again, I knew it was a simple solution, I just need to explore the methods a bit more next time.

    println for the win.

Similar Threads

  1. Remove duplicate lines from a text file
    By Dirt.Diver in forum New To Java
    Replies: 15
    Last Post: 06-25-2008, 02:08 PM
  2. Replies: 4
    Last Post: 06-09-2008, 04:44 PM
  3. writing text to file
    By notwist in forum New To Java
    Replies: 3
    Last Post: 04-25-2008, 04:20 AM
  4. how do i write to a text file from an arraylist?
    By otoro_java in forum New To Java
    Replies: 3
    Last Post: 01-30-2008, 06:53 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •