Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Page 1 of 2 12 LastLast
Results 1 to 25 of 29

Thread: Help with code

  1. #1
    Member
    Join Date
    Jan 2011
    Posts
    78
    My Mood
    Confused
    Thanks
    23
    Thanked 1 Time in 1 Post

    Question Help with code

    K, I'm basically brand new to java and have to do an assignment way beyond anything I've learned.

    this is what im trying to accomplish:

    Specification





    So right now I'm trying to work on creating a class "Student" that has all those fields and methods. Then somehow once I have all that I've got to figure out how to get that into an array that can make more students with that information and stuff etc. I'm confused and barely know how to make an array. =S
    It would be helpful if someone told me how to call an array without a pre-set amount of items in the list.

    Anyway this is what I have so far:

    For my menu:



     
    package ArrayList;
     
    import java.util.Scanner;
     
    public class Menu {
     
    	public static void main( String[] args )
    	{
    	System.out.println("Welcome!");
     
    Scanner input = new Scanner (System.in);
     
    	int UR; //user Response 1
    	System.out.println("Please type the number of the task you would like to perform.");
    	System.out.println("1. Add a student");
    	System.out.println("2. Find a student");
    	System.out.println("3. Delete a student");
    	System.out.println("4. Display all students");
    	System.out.println("5. Display the total number of students");
    	System.out.println("6. Exit");
     
    	UR = input.nextInt();
     
    	if (UR == 1){
    		Student sDisplay = new Student();
     
    		sDisplay.Display(); 
    	}
     
     
    }
    }

    For my Student:


     
     
    package ArrayList;
     
    public class Student {
     
    	String fName;
    	String lName;
    	int sNumber;
    	String Major;
    	Double GPA;
    	static int Count;
     
    	public void fName() {
     
    		fName = "Sarah";
     
    	}
     
    	public void lName() {
     
    		lName = "Somethin";
     
    	}
     
    	public void sNumber() {
     
    		sNumber = 1;
     
    	}
     
    	public void Major() {
     
    		Major = "Computer Science";
    	}
     
    	public void GPA() {
    		GPA = 4.0;
    	}
     
    	public static void Count() {
    		Count = 0;
    	}
     
    	public void Display() {
     
     
    		Student firstName = new Student();
    		firstName.fName();
     
    		System.out.printf("The name is: %d\n", GPA);
     
    		System.out.print(fName);
    	}
     
    }

    __________________________________________________ ______________________
    When I ran my program what I expected to get was this:
    The name is: 4.0
    Sarah


    But when I run it with user input 1
    I get:
    1
    The name is: null
    null


    Yes, what im trying to accomplish there doesn't relate to assignment specifically but how am I suppose to get it to work? and why isn't the name being assigned to the String or the int receiving its number? (I'm assuming its cause its only running through part of the program. or that particular class. which is why I tried to make Display call fName and run it so its assigned. But it didn't work and I'm obviously confused.) =S
    Basically I need as much help as I can get with this, especially with the arrays. So thanks in advance.
    Last edited by Hallowed; May 4th, 2011 at 11:14 AM.


  2. #2
    Forum Squatter newbie's Avatar
    Join Date
    Nov 2010
    Location
    North Wales
    Posts
    660
    My Mood
    Stressed
    Thanks
    28
    Thanked 115 Times in 106 Posts
    Blog Entries
    1

    Default Re: Help with code

    Ok here's the deal. If this really is your first introduction to Java and your tutor has given you this, then in my opinion he's a complete a*se.
    Reason for you getting null was that you were creating a new object from your object, so it was returning empty, appart from "The name is: null" where you were initialising fName, but printing GPA.
    Now, I will give you the majority of the Student class out of pity .

    public class Student {
     
        private String fName;
        private String lName;
        private int sNumber;
        private String major;
        private double gpa;
        static int count;
     
        public Student(String fName, String lName, int sNumber, String major, double gpa) {
            this.fName = fName;
            this.lName = lName;
            this.sNumber = sNumber;
            this.major = major;
            this.gpa = gpa;
     
            count++;//increment when object is created
        }
     
        //setter methods
        public void setForeName(String name) {
            fName = name;
        }
     
        public void setLastName(String lastName) {
            lName = lastName;
        }
     
        public void setStudentNumber(int sNo) {
            sNumber = sNo;
        }
     
        public void setMajor(String maj) {
            major = maj;
        }
     
        public void setGPA(double val) {
            gpa = val;
        }
     
        //getter methods - use to return values
        public String getForeName() {
            return fName;
        }
     
        public String getLastName() {
            return lName;
        }
     
        public int getStudentNumber() {
            return sNumber;
        }
     
        public String getMajor() {
            return major;
        }
     
        public double getGPA() {
            return gpa;
        }
     
        public static int getCount() {
            return count;
        }
     
        @Override
        public String toString() {
            return String.format("First name is: %s, Last name is: %s, Student "
                    + "Number is: %d, Major is: %s, GPA is: %.2f", fName, lName, sNumber, major, gpa);
        } //called automatically when you attempt to print an object - System.out.println(myObject);
    }

    Now from that, attempt to get your program running. Forget about Array Lists for a second, and just figure out how to get Menu working.

    Anything you're uncertain about, ask away.. but If you could go away and try complete Menu for a while now.. come back when you're stuck.
    Good luck.
    Last edited by newbie; January 22nd, 2011 at 12:40 PM.
    Please use [highlight=Java]//code goes here...[/highlight] tags when posting your code

  3. The Following User Says Thank You to newbie For This Useful Post:

    Hallowed (January 22nd, 2011)

  4. #3
    Member
    Join Date
    Jan 2011
    Posts
    78
    My Mood
    Confused
    Thanks
    23
    Thanked 1 Time in 1 Post

    Default Re: Help with code

    Hey thank you so much, your a saint. I'll try working with this.

  5. #4
    Member
    Join Date
    Jan 2011
    Posts
    78
    My Mood
    Confused
    Thanks
    23
    Thanked 1 Time in 1 Post

    Default Re: Help with code

    I feel like I'm not making much progress here. Everything is underlined in red and complaining at me =S

     
    package ArrayList;
     
    import java.util.Scanner;
     
    public class Menu {
     
    	public static void main(String[] args) {
    		System.out.println("Welcome!");
     
    		Scanner input = new Scanner(System.in);
     
    		int UR; // user Response 1
    		System.out.println("Please type the number of the task you would like to perform.");
    		System.out.println("1. Add a student");
    		System.out.println("2. Find a student");
    		System.out.println("3. Delete a student");
    		System.out.println("4. Display all students");
    		System.out.println("5. Display the total number of students");
    		System.out.println("6. Exit");
     
    		UR = input.nextInt();
     
    		if (UR == 1) {
     
    			public Student = ( String fName )  //initializes Student fName?
    			{
    				foreName = fName();
    			}
     
     
    			public void setForeName ( String fName) // method to set the students first name?
    			{
    				fName = input.nextInt();
    			}
     
     
    		if (UR == 4)	{
    			public String getForeName() // method to retrieve the students first name?
    			{
    				return fName;
     
    			}
     
    		}
     
    }

    I'm trying to go through this massive text book I have and trying to figure out how to correctly call and use the methods or classes in Student, but obviously its not working out to well. I don't know what I need to do with the arguments or how to return stuff.

    Also how do I use the
    @Override
    public String toString() {

    part?

  6. #5
    Forum Squatter newbie's Avatar
    Join Date
    Nov 2010
    Location
    North Wales
    Posts
    660
    My Mood
    Stressed
    Thanks
    28
    Thanked 115 Times in 106 Posts
    Blog Entries
    1

    Default Re: Help with code

    Yeah, Ok firstly start removing all code within your IF statements, its basically all wrong
    You've already defined those methods in Student, no need to do them again.

    Student newStudent = new Student("myFirstName","mySurname", 123, "my major, 1.2);

    That line will create a brand new student for you.
    so when you call
    newStudent.getForeName() and print it out like this..
    System.out.println(newStudent.getForeName()); it will return "myFirstName"

    if you printout the object like this;
    System.out.println(newStudent);
    It will print the all the information in the format specified in the toString() method of Student.
    -Note: toString() method is called automatically when you try printing the whole object like above.

    Hope that helps, ask if you need more info.
    Last edited by newbie; January 22nd, 2011 at 05:50 PM.
    Please use [highlight=Java]//code goes here...[/highlight] tags when posting your code

  7. The Following User Says Thank You to newbie For This Useful Post:

    Hallowed (January 22nd, 2011)

  8. #6
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Help with code

    public Student = ( String fName )

    should be, maybe

    public Student(String fName)

  9. #7
    Member
    Join Date
    Jan 2011
    Posts
    78
    My Mood
    Confused
    Thanks
    23
    Thanked 1 Time in 1 Post

    Default Re: Help with code

    So this line [ Student newStudent = new Student("myFirstName","mySurname", 123, "my major, 1.2); ]
    will create a new student in an array? with the name "myFirstName" and all the other values following correct?

    If I wanted the user to be able to put in specific information could I use some code like:


     
    String = cStudent
     
    Scanner input = new Scanner (System.in);
     
    System.out.println("Please input the new students information in this format:"myFirstName","mySurname", 123, "my major, 1.2");
     
    cStudent = input.nextInt();
     
    Student newStudent = new Student(cStudent);



    or if i wanted use like 5 variables and prompt them to enter the information one at a time?

    .. I guess I'll go try, it wasn't working and i was going to ask why its not getting my inputs but making this I realized what the problem is.

  10. #8
    Member
    Join Date
    Jan 2011
    Posts
    78
    My Mood
    Confused
    Thanks
    23
    Thanked 1 Time in 1 Post

    Default Re: Help with code

    K so I'm guessing if I want to be able to do that I have to have them put the information in one at a time.. especially since its not liking that I have lots of " " in the statement.

    But right now my problem here is that I cant even get it to print the user response #5 "this is a test"
    It just acts like the input had no effect? o_O So i can't really test if any of its working until I figure out why its not displaying that, or whats stopping it from making it to that point.

     
    package ArrayList;
     
    import java.util.Scanner;
     
    public class Menu {
     
    	public static void main(String[] args) {
    		System.out.println("Welcome!");
     
    		int UR = 0; // user Response 1
     
    		String createStudent = ("x");
     
    		System.out
    				.println("Please type the number of the task you would like to perform.");
    		System.out.println("1. Add a student");
    		System.out.println("2. Find a student");
    		System.out.println("3. Delete a student");
    		System.out.println("4. Display all students");
    		System.out.println("5. Display the total number of students");
    		System.out.println("6. Exit");
     
    		while (UR != 6) {
     
    			Scanner input = new Scanner (System.in); // ask for user response.
    			UR = input.nextInt(); //set UR equal to the users response.
     
     
     
    			if (UR == 1) {
    				Student newStudent = new Student("myFirstName", "mySurname",
    						123, "my major", 1.2);  //Create new student.
     
    				System.out.print("Success ");
    				System.out.print(newStudent.getForeName()); 
    				System.out.print(" account has been created.");  //Print verification.
     
     
    				//ask user for a new students information in exact form.
    				System.out.println("Please input the new students information in this format: "myFirstName","mySurname", 123, "my major", 1.2");
    				Scanner input = new Scanner (System.in);
    				createStudent = input.nextInt();
     
    				Student newStudent = new Student(createStudent);
    			}
     
    			UR = input.nextInt();
     
    			if (UR == 2) {
     
    			}
     
    			UR = input.nextInt();
     
    			if (UR == 3) {
     
    			}
     
    			UR = input.nextInt();
     
    			if (UR == 4) {
     
    			}
     
    			UR = input.nextInt();
     
    			if (UR == 5) {
    				System.out.println("this is a test");
    			}
     
    			UR = input.nextInt();
     
    			if (UR == 6) {
    				System.out.println("Good bye!");
    				System.exit(0);
    				System.out.println("This shouldn't display...");
    			}
    		}
    	}
    }

  11. #9
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Help with code

    I've seen inner methods a few time, but don't really think this is where you should have your Constructor and stuff inside the main method.

    package ArrayList;
     
    // to import a package, put "import java.util.ArrayList.*;" // don't have quotes like that
     
     
     
    import java.util.Scanner;
    import java.util.ArrayList;
     
    public class Menu {
     
    private String fName;
    private ArrayList<Student> studentList;
      public Student(String fName) //initializes Student fName?
                {
    this.fName = fName;
                    setForeName(fName);
    studentList = new ArrayList<Student>();
                }
     
    public void setForeName ( String fName) // method to set the students first name?
                {
                    this.fName = fName;
                }
     
      public String getForeName() // method to retrieve the students first name?
                {
                    return fName;
     
                }
     
    public String getAllStudents()
    {
    return (studentList.toString());
    }
     
    public int getNumberOfStudent()
    {
    return(studentList.size());
    }
     
        public static void main(String[] args) {
            System.out.println("Welcome!");
     
            Scanner input = new Scanner(System.in);
     
            int UR; // user Response 1
            System.out.println("Please type the number of the task you would like to perform.");
            System.out.println("1. Add a student");
            System.out.println("2. Find a student");
            System.out.println("3. Delete a student");
            System.out.println("4. Display all students");
            System.out.println("5. Display the total number of students");
            System.out.println("6. Exit");
     
            UR = input.nextInt();
     
            if (UR == 1) {
    System.out.println("Enter a fName");
     
    String fName = input.nextLine();
     
    Student temp = new Student(fName);
    studentList.add(temp);
     
    // not sure how you want to deal with finding the Student.  What to display.
    // Use the get(int index) method of the ArrayList class by calling studentList.get(index)
     
     
               }
               else if (UR == 3)
    {
    System.out.println("Enter the position of the student to remove.")
     
    int position = input.nextInt();
     
    if (position < 0 || position >= studentList.size())
    {
    System.out.println("Impossible");
    }
     
    else
    {
    studentList.remove(position);
    }
     
     
    }
     
     
     
       else     if (UR == 4)    {
     
               System.out.println(getAllStudents());
            }
     
    else if (UR == 5)
    {
    System.out.println(getNumberOfStudents());
    }
     
    }

  12. #10
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Help with code

    A String can only be a String.

    Setting a String value to an int won't work.

    String createStudent = ("x");

    Also, it'd be

    String createStudent = "x";

    () is for method parameters and constructor parameters.

  13. The Following User Says Thank You to javapenguin For This Useful Post:

    Hallowed (January 22nd, 2011)

  14. #11
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Help with code

    You have a class called Menu.

    Hmmmmm...unless Student is an inner class, which it could be I suppose, it probably should be in another .java file.

    If you make it an inner class, then you have to have
     
    public class Menu
    {
     
    private ArrayList<Student> studentList;
     
    private class Student
    {
    // in addition to your constructor for the Student class.
     
    // You need a Student constructor and a few variables in your Student class
    private String firstName;
    private String surName;
    private int something;
    private String majork
    private double GPAPerhaps;
    public Student(String firstName, String surName, int something, String major, double GPAPerhaps)
    {
    this.firstName = firstName;
    setFirstName(firstName);
    this.surName = surName;
    setSurName(surName);
    this.something = something;
    setSomething(something); // I don't know what the 123 stands for so I'm calling it "Something" for now.
    this.major = major;
    setMajor(major);
    this.GPAPerhaps = GPAPerhaps;
    setGPA(GPAPerhaps);
    }
     
    public void setFirstName(String firstName)
    {
    this.firstName = firstName;
    }
     
    public String getFirstName()
    {
    return firstName;
    }
     
    public void setSurName(String surName)
    {
    this.surName = surName;
    }
     
    public String getSurName()
    {
    return surName;
    }
     
    public String getName()
    {
    return (getFirstName() + " " + getSurName());
    }
     
    public void setSomething(int something)
    {
    this.something = something;
    }
     
    public int getSomething()
    {
    return something;
    }
     
    public void setGPA(double GPAPerhaps)
    {
    this.GPAPerhaps = GPAPerhaps;
    }
     
    public doulbe getGPA()
    {
    return GPAPerhaps;
    }
     
    public void setMajor(String major)
    {
    this.major = major;
    }
     
    public String getMajor()
    {
    return major;
    }
     
    public String toString()
    {
    String str = "Student Name is: " + getName() + ". Student something is: " + getSomething() + ".  Student major is: " + getMajor() + ".  Student GPA is: " + getGPA() + ".";
    return str;
    }
     
    }
     
    public Menu()
    {
    studentList = new ArrayList<Student>();
    }
     
     
    public String getAllStudents()
    {
    return (studentList.toString());
    }
     
    public int getNumberOfStudent()
    {
    return(studentList.size());
    }
     
        public static void main(String[] args) {
            System.out.println("Welcome!");
     
            Scanner input = new Scanner(System.in);
     
            int UR; // user Response 1
            System.out.println("Please type the number of the task you would like to perform.");
            System.out.println("1. Add a student");
            System.out.println("2. Find a student");
            System.out.println("3. Delete a student");
            System.out.println("4. Display all students");
            System.out.println("5. Display the total number of students");
            System.out.println("6. Exit");
     
            UR = input.nextInt();
     
            if (UR == 1) {
    System.out.println("Enter a fName");
     
    String fName = input.nextLine();
    System.out.println("Enter a last name");
    String lName = input.nextLine();
     
    System.out.println("Enter a something");
     
    int something2 = input.nextInt();
     
    System.out.println("Enter a major");
     
    String major = input.nextLine();
     
    System.out.println("Enter a G.P.A.");
     
    double GPA = input.nextDouble();
     
    Student temp = new Student(fName, lName, something2, major, GPA);
     
    studentList.add(temp);
     
    // not sure how you want to deal with finding the Student.  What to display.
    // Use the get(int index) method of the ArrayList class by calling studentList.get(index)
     
     
               }
               else if (UR == 3)
    {
    System.out.println("Enter the position of the student to remove.")
     
    int position = input.nextInt();
     
    if (position < 0 || position >= studentList.size())
    {
    System.out.println("Impossible");
    }
     
    else
    {
    studentList.remove(position);
    }
     
     
    }
     
     
     
       else     if (UR == 4)    {
     
               System.out.println(getAllStudents());
            }
     
    else if (UR == 5)
    {
    System.out.println(getNumberOfStudents());
    }
     
    }
    }
    }
    Last edited by javapenguin; January 22nd, 2011 at 07:06 PM.

  15. #12
    Forum Squatter newbie's Avatar
    Join Date
    Nov 2010
    Location
    North Wales
    Posts
    660
    My Mood
    Stressed
    Thanks
    28
    Thanked 115 Times in 106 Posts
    Blog Entries
    1

    Default Re: Help with code

    Penguin, he already has the setters and getters in another class, so the added code was not needed.
    -Hallowed, reason you couldn't get 5 to work was because you were redeclaring the input scanner before each option, which is not necessary, only do it the once up top.
    Creating a Student object does not add it into an ArrayList, you will need to do that yourself later.

    The following could be used to create a new Student object.
    So when user selects one.. do this:
            System.out.println("Enter Firstname:> ");
            String forename = "";
            while (forename.isEmpty()) {
                forename = input.nextLine();
            }
     
            System.out.println("Enter Surname:> ");
            String surname = "";
            while (surname.isEmpty()) {
                surname = input.nextLine();
            }
     
            System.out.println("Enter Student Number:> ");
            int studNo = -1;
            while (studNo < 0) {
                studNo = input.nextInt();
            }
     
            System.out.println("Enter Major:> ");
            String studentMajor = "";
            while (studentMajor.isEmpty()) {
                studentMajor = input.nextLine();
            }
     
            System.out.println("Enter GPA:> ");
            double gpa = -1.0;
            while (gpa < 0) {
                gpa = input.nextDouble();
            }
     
            Student newStudent = new Student(forename, surname, studNo, studentMajor, gpa);
    Please use [highlight=Java]//code goes here...[/highlight] tags when posting your code

  16. #13
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Help with code

    Quote Originally Posted by newbie View Post
    Penguin, he already has the setters and getters in another class, so the added code was not needed.
    -Hallowed, reason you couldn't get 5 to work was because you were redeclaring the input scanner before each option, which is not necessary, only do it the once up top.
    Creating a Student object does not add it into an ArrayList, you will need to do that yourself later.

    The following could be used to create a new Student object.
    So when user selects one.. do this:
            System.out.println("Enter Firstname:> ");
            String forename = "";
            while (forename.isEmpty()) {
                forename = input.nextLine();
            }
     
            System.out.println("Enter Surname:> ");
            String surname = "";
            while (surname.isEmpty()) {
                surname = input.nextLine();
            }
     
            System.out.println("Enter Student Number:> ");
            int studNo = -1;
            while (studNo < 0) {
                studNo = input.nextInt();
            }
     
            System.out.println("Enter Major:> ");
            String studentMajor = "";
            while (studentMajor.isEmpty()) {
                studentMajor = input.nextLine();
            }
     
            System.out.println("Enter GPA:> ");
            double gpa = -1.0;
            while (gpa < 0) {
                gpa = input.nextDouble();
            }
     
            Student newStudent = new Student(forename, surname, studNo, studentMajor, gpa);
    I think you only create a new Student object when you add it to the ArrayList.

    The way you're doing it now could work, though it should also be changed to stop it being above like a 4 or 5 for GPA.

  17. #14
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Help with code

    public class Menu
    {
     
    private ArrayList<Student> studentList;
     
    private class Student
    {
    // in addition to your constructor for the Student class.
     
    // You need a Student constructor and a few variables in your Student class
    private String firstName;
    private String surName;
    private int something;
    private String majork
    private double GPAPerhaps;
    public Student(String firstName, String surName, int something, String major, double GPAPerhaps)
    {
    this.firstName = firstName;
    setFirstName(firstName);
    this.surName = surName;
    setSurName(surName);
    this.something = something;
    setSomething(something); // I don't know what the 123 stands for so I'm calling it "Something" for now.
    this.major = major;
    setMajor(major);
    this.GPAPerhaps = GPAPerhaps;
    setGPA(GPAPerhaps);
    }
     
    public void setFirstName(String firstName)
    {
    this.firstName = firstName;
    }
     
    public String getFirstName()
    {
    return firstName;
    }
     
    public void setSurName(String surName)
    {
    this.surName = surName;
    }
     
    public String getSurName()
    {
    return surName;
    }
     
    public String getName()
    {
    return (getFirstName() + " " + getSurName());
    }
     
    public void setSomething(int something)
    {
    this.something = something;
    }
     
    public int getSomething()
    {
    return something;
    }
     
    public void setGPA(double GPAPerhaps)
    {
    this.GPAPerhaps = GPAPerhaps;
    }
     
    public doulbe getGPA()
    {
    return GPAPerhaps;
    }
     
    public void setMajor(String major)
    {
    this.major = major;
    }
     
    public String getMajor()
    {
    return major;
    }
     
    public String toString()
    {
    String str = "Student Name is: " + getName() + ". Student something is: " + getSomething() + ".  Student major is: " + getMajor() + ".  Student GPA is: " + getGPA() + ".";
    return str;
    }
     
    }
     
    public Menu()
    {
    studentList = new ArrayList<Student>();
    }
     
     
    public String getAllStudents()
    {
    return (studentList.toString());
    }
     
    public int getNumberOfStudent()
    {
    return(studentList.size());
    }
     
        public static void main(String[] args) {
            System.out.println("Welcome!");
     
            Scanner input = new Scanner(System.in);
     
            int UR; // user Response 1
            System.out.println("Please type the number of the task you would like to perform.");
            System.out.println("1. Add a student");
            System.out.println("2. Find a student");
            System.out.println("3. Delete a student");
            System.out.println("4. Display all students");
            System.out.println("5. Display the total number of students");
            System.out.println("6. Exit");
     
            UR = input.nextInt();
     
            if (UR == 1) {
     
     
     
    System.out.println("Enter Firstname:> ");
            String forename = "";
            while (forename.isEmpty()) {
                forename = input.nextLine();
            }
     
            System.out.println("Enter Surname:> ");
            String surname = "";
            while (surname.isEmpty()) {
                surname = input.nextLine();
            }
     
            System.out.println("Enter Student Number:> ");
            int studNo = -1;
            while (studNo < 0) {
                studNo = input.nextInt();
            }
     
            System.out.println("Enter Major:> ");
            String studentMajor = "";
            while (studentMajor.isEmpty()) {
                studentMajor = input.nextLine();
            }
     
            System.out.println("Enter GPA:> ");
            double gpa = -1.0;
            while (gpa < 0) {
                gpa = input.nextDouble();
            }
     
            Student newStudent = new Student(forename, surname, studNo, studentMajor, gpa);
     
     
     
    studentList.add(newStudent);
     
    // not sure how you want to deal with finding the Student.  What to display.
    // Use the get(int index) method of the ArrayList class by calling studentList.get(index)
     
     
               }
               else if (UR == 3)
    {
    System.out.println("Enter the position of the student to remove.")
     
    int position = input.nextInt();
     
    if (position < 0 || position >= studentList.size())
    {
    System.out.println("Impossible");
    }
     
    else
    {
    studentList.remove(position);
    }
     
     
    }
     
     
     
       else     if (UR == 4)    {
     
               System.out.println(getAllStudents());
            }
     
    else if (UR == 5)
    {
    System.out.println(getNumberOfStudents());
    }
     
    }
    }
    }
    Last edited by javapenguin; January 22nd, 2011 at 07:24 PM.

  18. #15
    Forum Squatter newbie's Avatar
    Join Date
    Nov 2010
    Location
    North Wales
    Posts
    660
    My Mood
    Stressed
    Thanks
    28
    Thanked 115 Times in 106 Posts
    Blog Entries
    1

    Default Re: Help with code

    To add to my code, you simply add the object into the ArrayList after creating it, but I didn't want to burden Hallowed with that until he got to the stage where he was comfortable with creating a new Student.

    "The way you're doing it now could work" Its how It does work... Another alternative is to have a third class, but by asking user to input every detail of the student, then making an object out of that information, then subsequently add that new object into an ArrayList, it allows for reusable code and its safe, as input will never be left empty.
    Last edited by newbie; January 22nd, 2011 at 07:36 PM.
    Please use [highlight=Java]//code goes here...[/highlight] tags when posting your code

  19. #16
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Help with code

    import java.util.Scanner.*;
    import java.util.ArrayList.*;
     
    public class Menu
    {
     
    private ArrayList<Student> studentList; // The ArrayListOfStudents
     
    // see ArrayList link after coding part ends.
     
    // this is the Student class.  It's an inner class right now, though it can be put in a separate .java file and changed to a public class if that's better for you
    private class Student
    {
    // in addition to your constructor for the Student class.
     
    // You need a Student constructor and a few variables in your Student class
    private String firstName; // firstName variable
    private String surName; // surName variable
    private int studentNumber; // studentNumber variable
    private String major;  // major variable
    private double GPA; // GPA variable
     
    // Student constructor
    public Student(String firstName, String surName, int studentNumber, String major, double GPA)
    {
    this.firstName = firstName; // sets first name variable to the variable firstName above
    setFirstName(firstName); // calls setFirstName(firstName) method
    this.surName = surName;
    setSurName(surName);
    this.studentNumber = studentNumber;
    setStudentNumber(studentNumber); 
    this.major = major;
    setMajor(major);
    this.GPA = GPA;
    setGPA(GPA);
    }
     
    public void setFirstName(String firstName)
    {
    this.firstName = firstName;
    }
     
    public String getFirstName()
    {
    return firstName;
    }
     
    public void setSurName(String surName)
    {
    this.surName = surName;
    }
     
    public String getSurName()
    {
    return surName;
    }
     
    public String getName()
    {
    return (getFirstName() + " " + getSurName());
    }
     
    public void setStudentNumber(int studentNumber)
    {
    this.studentNumber = studentNumber;
    }
     
    public int getStudentNumber()
    {
    return studentNumber;
    }
     
    public void setGPA(double GPA)
    {
    this.GPA = GPA;
    }
     
    public doulbe getGPA()
    {
    return GPA;
    }
     
    public void setMajor(String major)
    {
    this.major = major;
    }
     
    public String getMajor()
    {
    return major;
    }
     
    public String toString()
    {
    String str = "Student Name is: " + getName() + ". Student number is: " + getStudentNumber() + ".  Student major is: " + getMajor() + ".  Student GPA is: " + getGPA() + ".";
    return str;
    }
     
    }
     
    public Menu()
    {
    studentList = new ArrayList<Student>(); // an ArrayList of type Student
    }
     
     
    public String getAllStudents()
    {
    return (studentList.toString()); // returns a list of all the students in the ArrayList
    }
     
    public int getNumberOfStudent()
    {
    return(studentList.size()); // returns the number of students in the ArrayList
    }
     
        public static void main(String[] args) {
     
     
     
     
            System.out.println("Welcome!");
     
            Scanner input = new Scanner(System.in);
     
            int UR; // user Response 1
            System.out.println("Please type the number of the task you would like to perform.");
            System.out.println("1. Add a student");
            System.out.println("2. Find a student");
            System.out.println("3. Delete a student");
            System.out.println("4. Display all students");
            System.out.println("5. Display the total number of students");
            System.out.println("6. Exit");
     
            UR = input.nextInt();
     
            if (UR == 1) {
     
     
     
    System.out.println("Enter Firstname:> ");
            String forename = "";
            while (forename.isEmpty()) {
                forename = input.nextLine();
            }
     
            System.out.println("Enter Surname:> ");
            String surname = "";
            while (surname.isEmpty()) {
                surname = input.nextLine();
            }
     
            System.out.println("Enter Student Number:> ");
            int studNo = -1;
            while (studNo < 0) {
                studNo = input.nextInt();
            }
     
            System.out.println("Enter Major:> ");
            String studentMajor = "";
            while (studentMajor.isEmpty()) {
                studentMajor = input.nextLine();
            }
     
            System.out.println("Enter GPA:> ");
            double gpa = -1.0;
            while (gpa < 0) {
                gpa = input.nextDouble();
            }
     
            Student newStudent = new Student(forename, surname, studNo, studentMajor, gpa);
     
     
     
    studentList.add(newStudent); // adds the new Student to the Student ArrayList
    }
     
     
    else if (UR ==2)
    {
    int positionOfStudent = 0;
    System.out.println("Enter a student name.");
    String studentName = "";
     
    while (studentName.isEmpty())
    {
    studentName = input.nextLine();
    }
     
    boolean found = false;
    int i =0;
    while (found == false &&  positionOfStudent < studentList.size())
    {
    if (studentName.equalsIgnoreCase(studentList.get(i).getName()))
    {
    System.out.println("Student " + studentName + " found at position " + positionOfStudent + ".");
    found = true;
    }
     
    else
    {
    positionOfStudent++;
     
    }
    }
     
    if (found == false)
    System.out.println("Student not found.");
     
    else
    System.out.println(studentList.get(positionOfStudent).toString());
     
    }
     
     
               else if (UR == 3)
    {
    System.out.println("Enter the position of the student to remove.")
     
    int position = input.nextInt();
     
    if (position < 0 || position >= studentList.size())
    {
    System.out.println("Impossible");
    }
     
    else
    {
    studentList.remove(position);
    }
     
     
    }
     
     
     
       else     if (UR == 4)    {
     
               System.out.println(getAllStudents());
            }
     
    else if (UR == 5)
    {
    System.out.println(getNumberOfStudents());
    }
     
    else if (UR == 6)
    {
    System.out.println("Goodbye");
    // you need not have System.exit(0); I think as the while loop will enter after printing out the line above
    // as it's set to when 6 is entered and there's nothing after this while loop so the program should end.
    }
     
    else
    {
    System.out.println("Enter a number between 1 and 6.");
    }
    }
    }
    }
    H-SPHERE
    Last edited by javapenguin; January 22nd, 2011 at 08:30 PM.

  20. The Following User Says Thank You to javapenguin For This Useful Post:

    Hallowed (January 22nd, 2011)

  21. #17
    Forum Squatter newbie's Avatar
    Join Date
    Nov 2010
    Location
    North Wales
    Posts
    660
    My Mood
    Stressed
    Thanks
    28
    Thanked 115 Times in 106 Posts
    Blog Entries
    1

    Default Re: Help with code

    What was the point of posting that?
    You already know he has a separate Student class, so why even bother include it in the code?
    Please use [highlight=Java]//code goes here...[/highlight] tags when posting your code

  22. #18
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Unhappy Re: Help with code

    Why does it keeping saying "H-Sphere"?

    I keep telling it to say "ArrayList".

  23. #19
    Junior Member
    Join Date
    Jan 2011
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Help with code

    JP, you really shouldn't provide all the code like that. It's not really helping them.

  24. #20
    Member
    Join Date
    Jan 2011
    Posts
    78
    My Mood
    Confused
    Thanks
    23
    Thanked 1 Time in 1 Post

    Default Re: Help with code

    Eh, I'll have to go through it all anyway and make sure I can figure out what its doing, and I really appreciate ALL the help

    and thanks, I don't know what I was thinking telling it to get the input every time. =S I got it working now.


    This is a lot better than what I was thinking of doing. I didn't know you could have it check for empty strings.

            System.out.println("Enter Firstname:> ");
            String forename = "";
            while (forename.isEmpty()) {
                forename = input.nextLine();
            }
     
            System.out.println("Enter Surname:> ");
            String surname = "";
            while (surname.isEmpty()) {
                surname = input.nextLine();
            }
     
            System.out.println("Enter Student Number:> ");
            int studNo = -1;
            while (studNo < 0) {
                studNo = input.nextInt();
            }
     
            System.out.println("Enter Major:> ");
            String studentMajor = "";
            while (studentMajor.isEmpty()) {
                studentMajor = input.nextLine();
            }
     
            System.out.println("Enter GPA:> ");
            double gpa = -1.0;
            while (gpa < 0) {
                gpa = input.nextDouble();
            }
     
            Student newStudent = new Student(forename, surname, studNo, studentMajor, gpa);




    So if all this is not going into an array list, its all being stored into some virtual memory in the Student class right? Then once I have an array list built I can call it or return it? and have it placed in the arraylist?
    I guess this code right here
    	Student newStudent = new Student("myFirstName", "mySurname",
    						123, "my major", 1.2);  //Create new student.
    is creating a new class called newStudent? and then giving it all of that information by sending it to the setter methods. Then at somepoint I can send the newStudent class, to the array list. But if the user were going to continually use the create newStudent option from the menu, then I would also have to clear it out or call it again once its done? Is this done automatically once the code is run through? Or do I have to tell it to trash that information so I could make new, newStudent class?



    I'm confused about what is going on here. I don't know what "this." does exactly. But I'm assuming thats how your telling it, where to assign the code from above.
    public Student(String fName, String lName, int sNumber, String major, double gpa) {
            this.fName = fName;
            this.lName = lName;
            this.sNumber = sNumber;
            this.major = major;
            this.gpa = gpa;


    Another question is ||<-- these. I'm not even sure if I typed them right alt+(1,2,4). what do they mean/do? and how I'm normally suppose to type them? l l just two L's? l l I can't hardly tell what they are ha.
    Last edited by Hallowed; January 22nd, 2011 at 11:15 PM.

  25. #21
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Help with code

    Well, you can store all that stuff for1 Student without needing one. However, for a bunch of them...an ArrayList would be preferable as you'd have to create a new Student object by hand for every new one you made.

    ArrayLists can be added to or removed from, unlike arrays.

  26. #22
    Member
    Join Date
    Jan 2011
    Posts
    78
    My Mood
    Confused
    Thanks
    23
    Thanked 1 Time in 1 Post

    Default Re: Help with code

    import java.util.Scanner.*;
    import java.util.ArrayList.*;
    ^^What do the asterisks * at the end do? when I use them in eclipse it doesn't recognize the array list.

     
    package ArrayList;
     
    import java.util.Scanner;
    import java.util.ArrayList.*;
     
    public class Menu {
     
    	public static void main(String[] args) {
    		System.out.println("Welcome!");
     
    		int UR = 0; // user Response 1
     
    		System.out
    				.println("Please type the number of the task you would like to perform.");
    		System.out.println("1. Add a student");
    		System.out.println("2. Find a student");
    		System.out.println("3. Delete a student");
    		System.out.println("4. Display all students");
    		System.out.println("5. Display the total number of students");
    		System.out.println("6. Exit");
     
    		while (UR != 6) {
     
    			Scanner input = new Scanner(System.in); // ask for user response.
    			UR = input.nextInt(); // set UR equal to the users response.
     
    			if (UR == 1) {
    				System.out.println("Enter Firstname:> ");
    				String forename = "";
    				while (forename.isEmpty()) {
    					forename = input.nextLine();
    				}
     
    				System.out.println("Enter Surname:> ");
    				String surname = "";
    				while (surname.isEmpty()) {
    					surname = input.nextLine();
    				}
     
    				System.out.println("Enter Student Number:> ");
    				int studNo = -1;
    				while (studNo < 0) {
    					studNo = input.nextInt();
    				}
     
    				System.out.println("Enter Major:> ");
    				String studentMajor = "";
    				while (studentMajor.isEmpty()) {
    					studentMajor = input.nextLine();
    				}
     
    				System.out.println("Enter GPA:> ");
    				double gpa = -1.0;
    				while (gpa < 0) {
    					gpa = input.nextDouble();
    				}
     
    				Student newStudent = new Student(forename, surname, studNo,
    						studentMajor, gpa);
     
    				System.out.print("Success! ");
    				System.out.print(newStudent.getForeName());
    				System.out.println("'s account has been created with the following information:"); // Print verification.
    				System.out.println(newStudent);
    			}
     
    			if (UR == 2) {
     
    			}
     
    			if (UR == 3) {
     
    			}
     
    			if (UR == 4) {
     
    			}
     
    			if (UR == 5) {
    				System.out.println("this is a test");
    			}
     
    			if (UR == 6) {
    				System.out.println("Good bye!");
    				System.exit(0);
    			}
    		}
    	}
    }

    K so this all works great so far. Now I'm trying to create an arraylist using the code that penguin provided. Most of it makes sense, (except for the actual array part, I'm trying to work through it all and reading what I can about array's in my book, the code for the menu's all make sense though.) But I'm going to try building it in its own class. I don't want an inner class exactly if I actually know what I'm talking about haha.

    But I need to get information from the Student class once its created, into the Array List. How can I store all the students information in the array list? Because I thought an ArrayList will only hold a string, or an int. or something like that. How Could I * Store individual student records in an ArrayList? I can't see where in penguins code all this information is being stored for each student.
    It almost seems like I would have to create and arraylist
    String[ ] = StudentList ... eh nevermind scratch that because it wouldn't be a string, it would have to be a class? I would have assign each student their own class name, and then store the class in the arraylist some how?

    Also this code:
    Student newStudent = new Student("myFirstName", "mySurname",
                            123, "my major", 1.2);  //Create new student.
    created (From what I understand) a class called newStudent. But in the code above, for Menu #1, it fills in the information and I'm able to retrieve it and print it out again, but whats the name of the class its being stored in then? Or where is it being stored? I tried to call the class in another Menu # just for testing but realized that I couldn't because I don't know what the classes name is.
    Last edited by Hallowed; January 23rd, 2011 at 12:20 AM.

  27. #23
    Forum Squatter newbie's Avatar
    Join Date
    Nov 2010
    Location
    North Wales
    Posts
    660
    My Mood
    Stressed
    Thanks
    28
    Thanked 115 Times in 106 Posts
    Blog Entries
    1

    Default Re: Help with code

    Hey again hallowed.
    newStudent is an Object, i.e an instance of class Student.
    The information about newStudent is stored in newStudent Object, which has a memory reference (but forget this detail).

    To store the Object in an Array List you need to declare a generic ArrayList of type Student.
    Like this:
    Array List<Student> studentRecords = new ArrayList<Student>();

    Then the Array List is constructed.

    To insert a new Student object into the Array List, simply add
    studentRecords.add(newStudent);
    after...

                    Student newStudent = new Student(forename, surname, studNo,
                            studentMajor, gpa);

    Now your Array List is complete. So if you run 1 multiple times DURING the programs life-time, many Student Objects will be stored for you.

    To print all members in an Array List, you can you a for-each loop.
    for(Student s : studentRecords){
    //print s here
    }
    Please use [highlight=Java]//code goes here...[/highlight] tags when posting your code

  28. The Following User Says Thank You to newbie For This Useful Post:

    Hallowed (January 23rd, 2011)

  29. #24
    Member
    Join Date
    Jan 2011
    Posts
    78
    My Mood
    Confused
    Thanks
    23
    Thanked 1 Time in 1 Post

    Default Re: Help with code

    This:
    studentRecords.add(newStudent);
    would be presuming that I created my array in a class named studentRecords right?
    when I input that code it tells me that the method .add is undefined for the type studentRecords ....
    So I'm guessing I have to create some form of a method so that it places the newStudent call into the array? but I can't find a way to make a method that stores a class in the array. I made a method like it was asking for, I think.. but I don't know how to tell it to put that in..
    I feel handicapped. @_@ at least I'm learning lots.

    package ArrayList;
     
    import java.util.Scanner;
    import java.util.ArrayList.*;
     
    public class Menu {
     
    	public static void main(String[] args) {
    		System.out.println("Welcome!");
     
    		int UR = 0; // user Response 1
     
    		System.out
    				.println("Please type the number of the task you would like to perform.");
    		System.out.println("1. Add a student");
    		System.out.println("2. Find a student");
    		System.out.println("3. Delete a student");
    		System.out.println("4. Display all students");
    		System.out.println("5. Display the total number of students");
    		System.out.println("6. Exit");
     
    		while (UR != 6) {
     
    			Scanner input = new Scanner(System.in); // ask for user response.
    			UR = input.nextInt(); // set UR equal to the users response.
     
    			if (UR == 1) {
    				System.out.println("Enter Firstname:> ");
    				String forename = "";
    				while (forename.isEmpty()) {
    					forename = input.nextLine();
    				}
     
    				System.out.println("Enter Surname:> ");
    				String surname = "";
    				while (surname.isEmpty()) {
    					surname = input.nextLine();
    				}
     
    				System.out.println("Enter Student Number:> ");
    				int studNo = -1;
    				while (studNo < 0) {
    					studNo = input.nextInt();
    				}
     
    				System.out.println("Enter Major:> ");
    				String studentMajor = "";
    				while (studentMajor.isEmpty()) {
    					studentMajor = input.nextLine();
    				}
     
    				System.out.println("Enter GPA:> ");
    				double gpa = -1.0;
    				while (gpa < 0) {
    					gpa = input.nextDouble();
    				}
     
    				Student newStudent = new Student(forename, surname, studNo,
    						studentMajor, gpa);
     
     
    				studentRecords.add(newStudent);
     
     
    				System.out.print("Success! ");
    				System.out.print(newStudent.getForeName());
    				System.out.println("'s account has been created with the following information:"); // Print
    																									// verification.
    				System.out.println(newStudent);
    			}
     
    			if (UR == 2) {
     
    				int positionOfStudent = 0;
    				System.out.println("Enter a student name.");
    				String studentName = "";
     
    				while (studentName.isEmpty())
    				{
    				studentName = input.nextLine();
    				}
     
    				boolean found = false;
    				int i =0;
    				while (found == false &&  positionOfStudent < studentRecords.size())
    				{
    				if (studentName.equalsIgnoreCase(studentRecords.get(i).getName()))
    				{
    				System.out.println("Student " + studentName + " found at position " + positionOfStudent + ".");
    				found = true;
    			}
     
    			if (UR == 3) {
     
    			}
     
    			if (UR == 4) {
     
    				System.out.println(getAllStudents()); 
    			}
     
    			if (UR == 5) {
    				System.out.println("this is a test");
    			}
     
    			if (UR == 6) {
    				System.out.println("Good bye!");
    				System.exit(0);
    			}
    		}
    	}
    }


    package ArrayList;
     
    import java.util.ArrayList;
     
    public class studentRecords {
     
    	ArrayList<Student> studentRecords = new ArrayList<Student>();  // creates arraylist studentRecords
     
    	public static void add(Student newStudent) {
    		return (....)// TODO Auto-generated method stub
     
    	}
     
    	public String getAllStudents() {
    		return (studentRecords.toString()); // returns a list of all the students
    											// in the ArrayList
    	}
     
    	public int getNumberOfStudents() {
    		return (studentRecords.size()); // returns the number of students in the
    										// ArrayList
    	}
     
     
    }


    package ArrayList;
     
    public class Student {
     
        private String fName;
        private String lName;
        private int sNumber;
        private String major;
        private double gpa;
        static int count;
     
        public Student(String fName, String lName, int sNumber, String major, double gpa) {
            this.fName = fName;
            this.lName = lName;
            this.sNumber = sNumber;
            this.major = major;
            this.gpa = gpa;
     
            count++;//increment when object is created
        }
     
        //setter methods
        public void setForeName(String name) {
            fName = name;
        }
     
        public void setLastName(String lastName) {
            lName = lastName;
        }
     
        public void setStudentNumber(int sNo) {
            sNumber = sNo;
        }
     
        public void setMajor(String maj) {
            major = maj;
        }
     
        public void setGPA(double val) {
            gpa = val;
        }
     
        //getter methods - use to return values
        public String getForeName() {
            return fName;
        }
     
        public String getLastName() {
            return lName;
        }
     
        public int getStudentNumber() {
            return sNumber;
        }
     
        public String getMajor() {
            return major;
        }
     
        public double getGPA() {
            return gpa;
        }
     
        public static int getCount() {
            return count;
        }
     
        @Override
        public String toString() {
            return String.format("First name: %s, Last name: %s, Student "
                    + "Number: %d, Major: %s, GPA: %.2f", fName, lName, sNumber, major, gpa);
        } //called automatically when you attempt to print an object - System.out.println(myObject);
    }
    Last edited by Hallowed; January 23rd, 2011 at 08:22 PM.

  30. #25
    Member
    Join Date
    Jan 2011
    Posts
    78
    My Mood
    Confused
    Thanks
    23
    Thanked 1 Time in 1 Post

    Default Re: Help with code

    Well I came up with this code for it, and I think its actually storing the class in there. I just got to get it to work when I try to display it so I know if its working or not.

    import java.util.ArrayList;
     
    public class studentRecords {
     
    	static ArrayList<Student> studentRecords = new ArrayList<Student>();  // creates arraylist studentRecords
     
    	public static void add(Student newStudent) {
    		studentRecords.add(newStudent);
     
    	}

Page 1 of 2 12 LastLast