Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

[intro comp sci] I\'m having troubles with a question. I\'m having issues gettin

ID: 3672028 • Letter: #

Question

[intro comp sci]

I'm having troubles with a question. I'm having issues getting the same sample output and writing to textfile.

all code files: https://docs.google.com/document/d/1vNiQa_orgQjeugok9kjy_SPD_HPzwmEz9CMqajWC20w/edit?usp=sharing

original question:

Create a new Java file, and name it Database.java Name the class appropriately to match. You have been provided with a main program file called TestA2Q1.java Create two instance variables: String variables for the input and output file names. Botlh variables should be private. Please keep in mind that the input file and output file could be the same. Create only a single constructor that accepts two String parameters (the input and output file names) and initializes the two instance variables accordingly You have been provided with a sample input file called courses.txt. Each line in the input file contains all of the information for one course: a CRN, title, department, term and year separated by commas. A sample input file looks like this: 20161801,Advanced YouTube Commenting,Comp Sci,1,3 20162886,Zookeeping,Animal Science, 2,1 20162803, Intermediate Cereal Cooking,Culinary Arts,2,2 20163084, Potato Trees,Agriculture, 3,2 20161885, Paper Airplanes,Mechanical Engineering,1,4 20162803, Intermediate Cereal Cooking, Culinary Arts,2,2 28161082,Basket Weaving, Fine Arts,1,1 Write the following two methods for this class public CourseListQ2 load) This method will read the comma separated input file (specified in the constructor), line by line, create a Course object for each line, and add it to a new CourseListQ2 object that will be returned as the result. public void save (CourseListQ2 courseList) This method will store the CRN, title, department, term and year of each course in the courseList object, as a comma separated line, in the previously-specified output file, replacing anything that was in that file previously. Each course will be in a separate line

Explanation / Answer

TestA2Q1.java

package com.test.chegg;

public class TestA2Q1 {
   public static void main(String[] args) throws Exception {
       // Create a Database object and load the test file into it.
       Database courseList = new Database("course.txt", "coursesOut.txt");
       CourseListQ2 courses = courseList.load();

       // Add a new course and delete an existing course
       courses.addCourse(new Course("Aristotle", "Department of Philosophy",
               3, 2));
       courses.removeCourse("20161001");

       // Write out the contents of the database, and save it to a file.
       try {
           for (int i = 0; i <courses.getNumCourses(); i++)
               System.out.println(courses.getCourse(i).toCsv());
       } catch (ArrayIndexOutOfBoundsException e) {
           System.out.println("TestA2Q1: " + e);
       }
       try {
           courseList.save(courses);
       } catch (Exception e) {
           System.out.println("TestA2Q1: " + e);
       }

       System.out.println("End of processing. Programmed by Stew Dent.");
   }// main

}// TestA2Q1

Database.Java

package com.test.chegg;

import java.io.*;
import java.util.Scanner;

public class Database{
private String inputFile;
private String outputFile;
  
public Database(String input, String output){
this.inputFile = input;
this.outputFile = output;
}//constructor
  
public CourseListQ2 load(){
CourseListQ2 list = new CourseListQ2();
try{
Scanner in=new Scanner(new FileInputStream(inputFile));
while(in.hasNext()){
String line = in.nextLine();
String[] data = line.split(",");
try{
list.addCourse(new Course(data[0],data[1],data[2],
Integer.parseInt(data[3]),Integer.parseInt(data[4])));
}catch(Exception e){
System.out.println(e.getMessage());
}
}in.close();//closing the scanner
}catch(FileNotFoundException e){
System.err.println("file not found");
e.printStackTrace();
}return list;
}//read the comma separated input file
  
public void save(CourseListQ2 courseList){
try{
BufferedWriter b = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile)));
for(int i=0; i<courseList.getNumCourses(); i++){
b.write(courseList.getCourse(i).toCsv());
b.flush();//clearing the flush it means written all the content in buffered writer
b.newLine();

}b.close();//Closing the writer
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}//store the CRN title, department, term, and year
}

CourseListQ2.java

package com.test.chegg;

public class CourseListQ2 {
   private static final int INITIAL_NUM_COURSES = 5; // initial size of
                                                       // partially-full array

   private Course[] courses; // our partially-full, expanding array of Courses
   private int numCourses; // how many Courses we're actually storing

   // default constructor simply initializes our array
   // and sets our course count
   public CourseListQ2() {
       courses = new Course[INITIAL_NUM_COURSES];
       numCourses = 0;
   }// default constructor

   // takes a parameter representing a Course object and adds it
   // to our partially-full array; doubles the array size if necessary
   public void addCourse(Course course) throws Exception {
       Course[] newCourses;
       for (int i = 0; numCourses > 0 && i < numCourses; i++) {
           if (course.getCRN().equals(courses[i].getCRN())) {
               throw new Exception("Duplicate CRN: " + course.getCRN());
           }
       }
       // if we've run out of room in our array, we double its size
       if (numCourses == courses.length) {
           // create a blank array of twice the size of our current one
           newCourses = new Course[courses.length * 2];

           // copy our old elements into our new array
           System.arraycopy(courses, 0, newCourses, 0, numCourses);

           // re-direct our instance variable to point to the new array
           courses = newCourses;
       }// if

       // now add the course
       courses[numCourses] = course;
       numCourses++;
   }// addCourse

   // takes a String specifying the CRN of the course to remove;
   // returns Course reference if the course is found and deleted; null
   // otherwise
   public Course removeCourse(String crn) {
       Course result = null;
       int index = indexOf(crn); // simple linear search

       // course numbers must be positive
       if (index >= 0) {
           // Get the deleted course as our return result
           result = courses[index];
           // "Delete" the course by replacing it with the last course
           // reference
           courses[index] = courses[numCourses - 1];

           // we're done; subtract the number of courses and indicate success
           numCourses--;
       }// if

       return result;
   }// removeCourse

   // takes a String specifying the CRN of the course to search for;
   // returns the index if found, or -1 if not found
   public int indexOf(String crn) {
       int result = -1;
       int i = 0;

       // continue searching while (a) we haven't found our course, as long
       // as we're within the bounds of our array
       while (i < numCourses && result == -1) {
           if (courses[i].getCRN().equals(crn))
               result = i;
           i++;
       }// while

       return result;
   }// indexOf

   // returns a string showing the entire contents of the list
   public String toString() {
       String result = "There are " + numCourses + " courses available: ";
       int i;

       // loop through all of our courses and concatenate their string
       // representations
       for (i = 0; i < numCourses; i++)
           result += " " + courses[i] + ' ';

       return result;
   }// toString

   public int getNumCourses() {
       return numCourses;
   }

   public Course getCourse(int i) throws ArrayIndexOutOfBoundsException {
       if (i < 0 || i >= numCourses)
           throw new ArrayIndexOutOfBoundsException(
                   "getCourse received out of bounds index of" + numCourses);
       return courses[i];
   }
}// class CourseListQ2

Course.java

package com.test.chegg;

public class Course {
   private static final String YEAR = "2016"; // where to start numbering the
                                               // CRNs
   private static final String[] TERMS = { "Winter", "Spring", "Fall" };

   private static int numCourses = 0; // the number of Courses we've created so
                                       // far
   private static int nextCRN = 1;
   private String title; // the name of the course
   private String department; // who is offering the course
   private int term; // term offered; 1, 2 or 3
   private int year; // 1st year course, 2nd year course, etc.
   private String crn; // our unique ID, determined by numCourses

   // only constructor that we define; takes the title of the course, the
   // department
   // offering it, the term and the year (1st year, 2nd year, etc.) of the
   // course
   public Course(String title, String department, int term, int year) {
       this.title = title;
       this.department = department;
       this.term = term;
       this.year = year;
       numCourses++;

       crn = YEAR + this.term + String.format("%03d", numCourses);
       crn = String.valueOf(nextCRN);
       nextCRN++;
   }

   public Course(String newCRN, String title, String department, int term,
           int year) {
       this(title, department, term, year);
       int i = Integer.parseInt(newCRN);
       if (i > nextCRN) {
           crn = newCRN;
           nextCRN = i + 1;
       }
   }

   public String toCsv() {
       return crn + "," + title + "," + department + "," + TERMS[term - 1]
               + "," + year;
   }

   // returns this course's name
   public String getTitle() {
       return title;
   }

   // return the name of the department offering this course
   public String getDepartment() {
       return department;
   }

   // returns the year of the course (1st year, etc.)
   public int getYear() {
       return year;
   }

   // returns the term associated with this course
   public int getTerm() {
       return term;
   }

   // returns the CRN associated with this course
   public String getCRN() {
       return crn;
   }

   // handy method returning a string representation of this Course object
   public String toString() {
       return "CRN: " + crn + ": Term: " + TERMS[term - 1] + ", " + title
               + ", Dept: " + department + " (year " + year + ")";
   }
}

Note:They are only two mistakes in the program one is trying to acces the list unknown position and the second one is not flushing the buffered writer

public void save(CourseListQ2 courseList){
try{
BufferedWriter b = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile)));
for(int i=0; i<courseList.getNumCourses(); i++){
b.write(courseList.getCourse(i).toCsv());
b.flush();//clearing the flush it means written all the content in buffered writer
b.newLine();

}b.close();//Closing the writer
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}//store the CRN title, department, term, and year

Output:

20163008,Aristotle,Department of Philosophy,Fall,2
20162006,Zookeeping,Animal Science,Spring,1
20162007,Intermediate Cereal Cooking,Culinary Arts,Spring,2
20163004,Potato Trees,Agriculture,Fall,2
20163005,Paper Airplanes,Mechanical Engineering,Winter,4
20163006,Intermediate Cereal Cooking,Culinary Arts,Spring,2
20163007,Basket Weaving,Fine Arts,Winter,1
End of processing.
Programmed by Stew Dent.

Version2:

Course2.Java

package com.test.chegg;

public class Course {
   private static final String YEAR = "2016"; // where to start numbering the
                                               // CRNs
   private static final String[] TERMS = { "Winter", "Spring", "Fall" };

   private static int numCourses = 0; // the number of Courses we've created so
                                       // far
   private static int nextCRN = 1;
   private String title; // the name of the course
   private String department; // who is offering the course
   private int term; // term offered; 1, 2 or 3
   private int year; // 1st year course, 2nd year course, etc.
   private String crn; // our unique ID, determined by numCourses

   // only constructor that we define; takes the title of the course, the
   // department
   // offering it, the term and the year (1st year, 2nd year, etc.) of the
   // course
   public Course(String title, String department, int term, int year) {
       this.title = title;
       this.department = department;
       this.term = term;
       this.year = year;
       numCourses++;

   crn = YEAR + this.term + String.format("%03d", numCourses);
   //This Code was not needed
   //crn = String.valueOf(nextCRN);
   //nextCRN++;
   }

   public Course(String newCRN, String title, String department, int term,
           int year) {
       this(title, department, term, year);
       //int i = Integer.parseInt(newCRN);
   //if (i > nextCRN) {
       crn = newCRN;
           //nextCRN = i + 1;
   //   }
   }

   public String toCsv() {
       return crn + "," + title + "," + department + "," + term
               + "," + year;
   }

   // returns this course's name
   public String getTitle() {
       return title;
   }

   // return the name of the department offering this course
   public String getDepartment() {
       return department;
   }

   // returns the year of the course (1st year, etc.)
   public int getYear() {
       return year;
   }

   // returns the term associated with this course
   public int getTerm() {
       return term;
   }

   // returns the CRN associated with this course
   public String getCRN() {
       return crn;
   }

   // handy method returning a string representation of this Course object
   public String toString() {
       return "CRN: " + crn + ": Term: " + TERMS[term - 1] + ", " + title
               + ", Dept: " + department + " (year " + year + ")";
   }
}

Database.java

package com.test.chegg;

import java.io.*;
import java.util.Scanner;

public class Database{
private String inputFile;
private String outputFile;
  
public Database(String input, String output){
this.inputFile = input;
this.outputFile = output;
}//constructor
  
public CourseListQ2 load(){
CourseListQ2 list = new CourseListQ2();
try{
Scanner in=new Scanner(new FileInputStream(inputFile));
while(in.hasNext()){
String line = in.nextLine();
String[] data = line.split(",");
try{
list.addCourse(new Course(data[0],data[1],data[2],
Integer.parseInt(data[3]),Integer.parseInt(data[4])));
}catch(Exception e){
System.out.println(e.getMessage());
}
}
in.close();//closing the scanner
}catch(FileNotFoundException e){
System.err.println("file not found");
e.printStackTrace();
}return list;
}//read the comma separated input file
  
public void save(CourseListQ2 courseList){
try{
BufferedWriter b = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile)));
for(int i=0; i<courseList.getNumCourses(); i++){
b.write(courseList.getCourse(i).toCsv());
b.flush();//clearing the flush it means written all the content in buffered writer
b.newLine();

}b.close();//Closing the writer
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}//store the CRN title, department, term, and year
}

TestA2Q1.java

package com.test.chegg;

public class TestA2Q1 {
   public static void main(String[] args) throws Exception {
       // Create a Database object and load the test file into it.
       Database courseList = new Database("course.txt", "coursesOut.txt");
       CourseListQ2 courses = courseList.load();

       // Add a new course and delete an existing course
       courses.addCourse(new Course("Aristotle", "Department of Philosophy",
               3, 2));
       courses.removeCourse("20161001");

       // Write out the contents of the database, and save it to a file.
       try {
           for (int i = 0; i <courses.getNumCourses(); i++)
               System.out.println(courses.getCourse(i).toCsv());
       } catch (ArrayIndexOutOfBoundsException e) {
           System.out.println("TestA2Q1: " + e);
       }
       try {
           courseList.save(courses);
       } catch (Exception e) {
           System.out.println("TestA2Q1: " + e);
       }

       System.out.println("End of processing. Programmed by Stew Dent.");
   }// main

}// TestA2Q1

CourseListQ2.java

package com.test.chegg;

public class CourseListQ2 {
   private static final int INITIAL_NUM_COURSES = 5; // initial size of
                                                       // partially-full array

   private Course[] courses; // our partially-full, expanding array of Courses
   private int numCourses; // how many Courses we're actually storing

   // default constructor simply initializes our array
   // and sets our course count
   public CourseListQ2() {
       courses = new Course[INITIAL_NUM_COURSES];
       numCourses = 0;
   }// default constructor

   // takes a parameter representing a Course object and adds it
   // to our partially-full array; doubles the array size if necessary
   public void addCourse(Course course) throws Exception {
       Course[] newCourses;
       for (int i = 0; numCourses > 0 && i < numCourses; i++) {
           if (course.getCRN().equals(courses[i].getCRN())) {
               throw new Exception("Duplicate CRN: " + course.getCRN());
           }
       }
       // if we've run out of room in our array, we double its size
       if (numCourses == courses.length) {
           // create a blank array of twice the size of our current one
           newCourses = new Course[courses.length * 2];

           // copy our old elements into our new array
           System.arraycopy(courses, 0, newCourses, 0, numCourses);

           // re-direct our instance variable to point to the new array
           courses = newCourses;
       }// if

       // now add the course
       courses[numCourses] = course;
       numCourses++;
   }// addCourse

   // takes a String specifying the CRN of the course to remove;
   // returns Course reference if the course is found and deleted; null
   // otherwise
   public Course removeCourse(String crn) {
       Course result = null;
       int index = indexOf(crn); // simple linear search

       // course numbers must be positive
       if (index >= 0) {
           // Get the deleted course as our return result
           result = courses[index];
           // "Delete" the course by replacing it with the last course
           // reference
           courses[index] = courses[numCourses - 1];

           // we're done; subtract the number of courses and indicate success
           numCourses--;
       }// if

       return result;
   }// removeCourse

   // takes a String specifying the CRN of the course to search for;
   // returns the index if found, or -1 if not found
   public int indexOf(String crn) {
       int result = -1;
       int i = 0;

       // continue searching while (a) we haven't found our course, as long
       // as we're within the bounds of our array
       while (i < numCourses && result == -1) {
           if (courses[i].getCRN().equals(crn))
               result = i;
           i++;
       }// while

       return result;
   }// indexOf

   // returns a string showing the entire contents of the list
   public String toString() {
       String result = "There are " + numCourses + " courses available: ";
       int i;

       // loop through all of our courses and concatenate their string
       // representations
       for (i = 0; i < numCourses; i++)
           result += " " + courses[i] + ' ';

       return result;
   }// toString

   public int getNumCourses() {
       return numCourses;
   }

   public Course getCourse(int i) throws ArrayIndexOutOfBoundsException {
       if (i < 0 || i >= numCourses)
           throw new ArrayIndexOutOfBoundsException(
                   "getCourse received out of bounds index of" + numCourses);
       return courses[i];
   }
}// class CourseListQ2

Output:

Duplicate CRN: 20162003
20163008,Aristotle,Department of Philosophy,3,2
20162006,Zookeeping,Animal Science,2,1
20162003,Intermediate Cereal Cooking,Culinary Arts,2,2
20163004,Potato Trees,Agriculture,3,2
20161005,Paper Airplanes,Mechanical Engineering,1,4
20161002,Basket Weaving,Fine Arts,1,1
End of processing.
Programmed by Stew Dent.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote