Welcome to Dream.In.Code
Getting Java Help is Easy!

Join 136,272 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 2,244 people online right now. Registration is fast and FREE... Join Now!




Help with array output

 
Reply to this topicStart new topic

Help with array output, little problem here...

KaizokuXero
26 Aug, 2008 - 01:57 PM
Post #1

New D.I.C Head
*

Joined: 8 Aug, 2008
Posts: 7

OK here's my problem....I have to read from a text file in order to get the course object and split each course object into an array and then output whatever the user inputs into a txt file with String and double data...the problem is that the professor didn't even tell us how to actually do anything about arrays so I'm completely lost and whatever I have done so far is just out of sheer willpower and luck.

Can anyone help me find out where I'm going wrong?

it can read from the file but I don't know how to break the information into arrays but I can at least get the student names into a file...just not a text file...

Little help here please?




CODE
/*
    Class Project 4 Solution
*/

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

public class GradebookApp
{
    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 = "";
                ArrayList<String> students = new ArrayList<String>();

        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();

            try
            {

                File productsFile = new File("courses.txt");

                BufferedReader in = new BufferedReader(
                                new FileReader(productsFile));

//                String courseChoice = Validator.getStringYesNoAnswer(sc,"Would you like to add a course?: ");


                    String line = in.readLine();

                    String [] courses = line.split("\t");
                    String courseCode = courses [0];
                    String courseDescription = courses [1];

                    course.setCode(courseCode);
                    course.setTitle(courseDescription);

                    line = in.readLine();

            }

            catch(IOException ioe)
            {
                ioe.printStackTrace();
            }

                    System.out.println("Course Code: " + course.getCode());
                    System.out.println("Course Description: " + course.getTitle());
        //            System.out.println();




            //Check if the user wants to enter a student
               String addStudentChoice = Validator.getStringYesNoAnswer(sc,"Would you like to add a student?: ");
            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();

                students.add(undergraduateStudent.getName());
                //students.add(undergraduateStudent.getGrade());

                //Perform student calculations
                numberOfStudents += 1;
                highestGrade = Math.max(highestGrade,undergraduateStudent.getGrade());
                lowestGrade = Math.min(lowestGrade,undergraduateStudent.getGrade());
                totalGrades += undergraduateStudent.getGrade();

                addStudentChoice = Validator.getStringYesNoAnswer(sc,"Would you like to add another student?: ");
            }


            //Perform course calculations
            averageGrade = totalGrades/numberOfStudents;

            try
            {

                PrintWriter out = new PrintWriter(
                                  new BufferedWriter(
                                  new FileWriter(course.getCode())));

                out.print(students);
                out.close();
            }

            catch(IOException ioe)
            {
                ioe.printStackTrace();
            }



            //Output the results
            System.out.println();
            System.out.println("COURSE DATA:");
            System.out.println("Code: " + course.getCode());
            System.out.println("Title: " + course.getTitle());
            System.out.println("Number of Students: " + numberOfStudents);
            System.out.println("Highest Grade: " + highestGrade);
            System.out.println("Lowest Grade: " + lowestGrade);
            System.out.println("Average Grade: " + averageGrade);
            System.out.println("Average Letter Grade: " + Student.determineLetterGrade(averageGrade));
            System.out.println();

            //Ask if the user wants to add another class
            addClassChoice = Validator.getStringYesNoAnswer(sc,"Would you like to add another course?: ");

        }
        while (addClassChoice.equalsIgnoreCase("y"));

        //Output the total student object count
           System.out.println("Number of Student Objects:    " + Student.getCount());
           System.out.println();

    }
}


This post has been edited by KaizokuXero: 26 Aug, 2008 - 02:07 PM
User is offlineProfile CardPM
+Quote Post

pbl
RE: Help With Array Output
26 Aug, 2008 - 02:33 PM
Post #2

D.I.C Lover
Group Icon

Joined: 6 Mar, 2008
Posts: 3,110



Thanked: 202 times
Dream Kudos: 75
My Contributions
QUOTE(KaizokuXero @ 26 Aug, 2008 - 02:57 PM) *

OK here's my problem....I have to read from a text file in order to get the course object and split each course object into an array and then output whatever the user inputs into a txt file with String and double data...the problem is that the professor didn't even tell us how to actually do anything about arrays so I'm completely lost and whatever I have done so far is just out of sheer willpower and luck.

Can anyone help me find out where I'm going wrong?



Your arrays are OK the problem is that you do not save/re-create your course at every line
And you don't loop while reading every line from the file

Don't see your class Course but better to have a constructor that will receive the CourseCode and CourseDescription
Then you have to have an array of Course or even better an ArrayList. ArrayList are likes array but they grow as required contrarely to an array that has a fix length

CODE

ArrayList<Course> courseList = new ArrayList<Course>();

try {
   File productsFile = new File("courses.txt");

    BufferedReader in = new BufferedReader(new FileReader(productsFile));    // open file

    String line = in.readLine();              // read first line
    while(line != null)                           // while there are more lines
    {
           String [] courses = line.split("\t");                             // split
           Course c = new Course(courses[0]), couses[1]);       // create new course object
           couseList.add(c);                                                     // add it to the arrayList
           line = in.readLine();                                                 // read next line
     }
}
catch(........


CODE

// to display the couses included in the ArrayList
for(Course c : couseList) {
   System.out.println(c.getCode() + " " c.getTitle());
}


User is online!Profile CardPM
+Quote Post

KaizokuXero
RE: Help With Array Output
26 Aug, 2008 - 02:49 PM
Post #3

New D.I.C Head
*

Joined: 8 Aug, 2008
Posts: 7

I forgot to add the rest of the classes that I was using

/edit

pbl THANK YOU!!!! I've been hitting my head on the wall for hours trying to figure out what to do. Like I said I have no programming experience with this subject whatsoever so any little bit helps. The next thing I have to try to figure out is to how to code a PrintWriter to make a text file with the courseCode as the title and how to input the student name and grade into the file...


CODE


public class Course
{
    private String code;
    private String title;

    public Course()
    {
        this.code = "";
        this.title = "";
    }

    public Course(String code, String title)
    {
        this.code = code;
        this.title = title;
    }

    public String getCode()
    {
        return code;
    }

    public void setCode(String code)
    {
        this.code = code;
    }

    public String getTitle()
    {
        return title;
    }

    public void setTitle(String title)
    {
        this.title = title;
    }

}


CODE




public class Student
{
    private String name;
    private String email;
    private double grade;

    protected static int count = 0; // A protected static variable

    public Student()
    {
        name = "";
        email = "";
        grade = 0;
    }

    public Student(String name, String email, double grade)
    {
        this.name = name;
        this.email = email;
        this.grade = grade;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public String getEmail()
    {
        return email;
    }

    public void setEmail(String email)
    {
        this.email = email;
    }

    public Double getGrade()
    {
        return grade;
    }

    public void setGrade(Double grade)
    {
        this.grade = grade;
    }

    public String getLetterGrade()
    {
        String letterGrade = "";

        if (grade >= 90.0)
        {
            letterGrade = "A";
        }
        else if (grade >= 80.0)
        {
            letterGrade = "B";
        }
        else if (grade >= 70.0)
        {
            letterGrade = "C";
        }
        else if (grade >= 60.0)
        {
            letterGrade = "D";
        }
        else
        {
            letterGrade = "F";
        }

        return letterGrade;
    }

    public static String determineLetterGrade(double grade)
    {
        String letterGrade = "";

        if (grade >= 90.0)
        {
            letterGrade = "A";
        }
        else if (grade >= 80.0)
        {
            letterGrade = "B";
        }
        else if (grade >= 70.0)
        {
            letterGrade = "C";
        }
        else if (grade >= 60.0)
        {
            letterGrade = "D";
        }
        else
        {
            letterGrade = "F";
        }

        return letterGrade;
    }

    public static int getCount()
    {
        return count;
    }

}


CODE

public class UndergraduateStudent extends Student
{
    private String major;
    private String level;

    public UndergraduateStudent()
    {
        super();
        major = "";
        level = "";
        count++;
    }

    public String getMajor()
    {
        return major;
    }

    public void setMajor(String major)
    {
        this.major = major;
    }

    public String getLevel()
    {
        return level;
    }

    public void setLevel(String level)
    {
        this.level = level;
    }

}


CODE

import java.util.Scanner;

public class Validator
{

    public static double getDouble(Scanner sc, String prompt)
    {
        double d = 0;
        boolean isValid = false;

        while (isValid == false)
        {
            System.out.print(prompt);

            if (sc.hasNextDouble())
            {
                d = sc.nextDouble();
                isValid = true;
            }
            else
            {
                System.out.println("Error! Invalid decimal value. Try again.");
            }

            sc.nextLine();  // discard any other data entered on the line
        }

        return d;
    }

    public static double getDoubleWithinRange(Scanner sc, String prompt, double min, double max)
    {
        double d = 0;
        boolean isValid = false;

        while (isValid == false)
        {
            d = getDouble(sc, prompt);

            if (d < min)
            {
                System.out.println("Error! Number must be greater than or equal to " + min + ".");
            }
            else if (d > max)
            {
                System.out.println("Error! Number must be less than or equal to " + max + ".");
            }
            else
            {
                isValid = true;
              }
        }

        return d;
    }

    public static int getInt(Scanner sc, String prompt)
    {
        int i = 0;
        boolean isValid = false;

        while (isValid == false)
        {
            System.out.print(prompt);

            if (sc.hasNextInt())
            {
                i = sc.nextInt();
                isValid = true;
            }
            else
            {
                System.out.println("Error! Invalid integer value. Try again.");
            }

            sc.nextLine();  // discard any other data entered on the line
        }

        return i;
    }

    public static int getIntWithinRange(Scanner sc, String prompt, int min, int max)
    {
        int i = 0;
        boolean isValid = false;

        while (isValid == false)
        {
            i = getInt(sc, prompt);

            if (i < min)
            {
                System.out.println("Error! Number must be greater than or equal to " + min + ".");
            }
            else if (i > max)
            {
                System.out.println("Error! Number must be less than " + max + ".");
            }
            else
            {
                isValid = true;
            }
        }

        return i;
    }

    public static String getString(Scanner sc, String prompt)
    {
        System.out.print(prompt);
        String s = sc.nextLine();  // read user entry
        return s;
    }

    public static String getStringYesNoAnswer(Scanner sc, String prompt)
    {
        String s = "";
        boolean isValid = false;

        while (isValid == false)
        {
            s = getString(sc, prompt);

            if (s.equalsIgnoreCase("y") || s.equalsIgnoreCase("n"))
            {
                isValid = true;
            }
            else
            {
                System.out.println("Error! Invalid Entry! You must enter Y or N");
            }
        }

        return s;
    }

    public static String getStringWithinRange(Scanner sc, String prompt, int min, int max)
    {
        String s = "";
        boolean isValid = false;

        while (isValid == false)
        {
            s = getString(sc, prompt);

            if (s.length() < min)
            {
                System.out.println("Error! The string must be " + min + " or more characters.");
            }
            else if (s.length() > max)
            {
                System.out.println("Error! The string must must be " + max + " or fewer characters.");
            }
            else
            {
                isValid = true;
            }
        }

        return s;
    }
}


This post has been edited by KaizokuXero: 26 Aug, 2008 - 02:52 PM
User is offlineProfile CardPM
+Quote Post

KaizokuXero
RE: Help With Array Output
27 Aug, 2008 - 11:49 AM
Post #4

New D.I.C Head
*

Joined: 8 Aug, 2008
Posts: 7

ok well I got mostly everything working except I am at a lost with the arrayList portion.

I have it where I can loop through the objects and it prints everything out BUT I don't know how to get the undergraduateStudent portion of the name and the grade to the ArrayList. I was thinking of creating a student object in order to do it but does anyone know how to do this?

this is what I have so far...

CODE

/*
    Class Project 4 Solution
*/

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

public class GradebookApp
{
    public static Student student;
    public static UndergraduateStudent UndergraduateStudent;
    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();

            ArrayList<Course> courseList = new ArrayList<Course>();
            ArrayList<UndergraduateStudent> studentObject = new ArrayList<UndergraduateStudent>();

            try
            {

                File productsFile = new File("courses.txt");

                BufferedReader in = new BufferedReader(
                                new FileReader(productsFile));

                String line = in.readLine();

                    while (line != null)
                    {

                          String [] courses = line.split("\t");
                          Course c = new Course(courses[0], courses[1]);
                          courseList.add(c);

                           line = in.readLine();
                       }

                       if(line == null)
                        {
                            in.close();
                        }
            }

            catch(IOException ioe)
            {
                ioe.printStackTrace();
            }

            for(Course c : courseList)
            {
               System.out.println(c.getCode() + " " + c.getTitle());

                        //Check if the user wants to enter a student
               String addStudentChoice = Validator.getStringYesNoAnswer(sc,"Would you like to add a student?: ");
            while (addStudentChoice.equalsIgnoreCase("y"))
            {
                ArrayList<String> studentObjects = new ArrayList<String>();

                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();

                addStudentChoice = Validator.getStringYesNoAnswer(sc,"Would you like to add another student?: ");
            }



            //Perform course calculations
            averageGrade = totalGrades/numberOfStudents;

            //Output the results
            System.out.println();
            System.out.println("COURSE DATA:");
            System.out.println("Code: " + c.getCode());
            System.out.println("Title: " + c.getTitle());
            System.out.println("Number of Students: " + numberOfStudents);
            System.out.println("Highest Grade: " + highestGrade);
            System.out.println("Lowest Grade: " + lowestGrade);
            System.out.println("Average Grade: " + averageGrade);
            System.out.println("Average Letter Grade: " + Student.determineLetterGrade(averageGrade));
            System.out.println();


// ignore this area for now...this as a test.
//------------------------------------------------------------------------------------------------------------------------
                        try
                        {
                            PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(c.getCode() + ".txt")));
                            out.print(c.getCode());
                            out.print("\t");
                            out.print(c.getTitle());
                            out.close();

                        }

                        catch(IOException ioe)
                        {
                            ioe.printStackTrace();
                        }

//------------------------------------------------------------------------------------------------------------------------

            //Ask if the user wants to add another class
            addClassChoice = Validator.getStringYesNoAnswer(sc,"Would you like to add another course?: ");
            }
        }
        while (!addClassChoice.equalsIgnoreCase("n"));

        //Output the total student object count
           System.out.println("Number of Student Objects:    " + Student.getCount());
           System.out.println();

    }
}


this has been frustrating to say the least...I have to find a way to put the String name and the double grade into the ArrayList studentObject but again I have no clue...

User is offlineProfile CardPM
+Quote Post

pbl
RE: Help With Array Output
27 Aug, 2008 - 02:58 PM
Post #5

D.I.C Lover
Group Icon

Joined: 6 Mar, 2008
Posts: 3,110



Thanked: 202 times
Dream Kudos: 75
My Contributions
QUOTE(KaizokuXero @ 27 Aug, 2008 - 12:49 PM) *

ok well I got mostly everything working except I am at a lost with the arrayList portion.

I have it where I can loop through the objects and it prints everything out BUT I don't know how to get the undergraduateStudent portion of the name and the grade to the ArrayList. I was thinking of creating a student object in order to do it but does anyone know how to do this?

this is what I have so far...


Sure you can create a Student class as you created a Course class

CODE

class Student {
    String name;
    double grade;

    Student(String n, double g) {
        name = n;
        grade = g;
    }
}


An nothing should stop you to create an ArrayList of Students


User is online!Profile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic
Time is now: 12/2/08 05:01AM

Live Java Help!

Java Tutorials

Reference Sheets

Java Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month