Im trying to create a student class, a course class and the main class. I am trying to add students to the course, and when students are added to the class the number of students in the course should increase, when the the code is run it should print the course details followed by the students in the course.
I have got the following code:
Main class:
public class JavaLecture3 {
public static final int DEBUG = 0;
public static void main(String [] args){
//Student student = new Student(); // Calling default constructor here.
Course course = new Course();
student = new Student(21, "Joe", "CSE", "07447832342");
course = new Course("CSE", "Tom", 5);
System.out.println("Course Information: ");
System.out.println("-------------------");
System.out.println(course);
System.out.println();
System.out.println("Student contains: "); // calls student.toString());
System.out.println("-------------------");
System.out.println(student);
}
}
Course class:
public class Course {
ArrayList<Student> studentList;
private String courseName;
private String teacher;
private int noOfStudents;
//Getters
public String getCourseName(){
return this.courseName;
}
public int getNoOfStudents(){
return this.noOfStudents;
}
public String getTeacher(){
return this.teacher;
}
//Setters
public void setCourseName(String courseName){
this.courseName = courseName;
}
public void setNoOfStudents(int noOfStudents){
this.noOfStudents = noOfStudents;
}
public void setTeacher(String teacher){
this.teacher = teacher;
}
/**
* Default constructor. Populates course name, number of students with defaults
*
*/
public Course(){
this.noOfStudents = 0;
this.courseName = "Not Set";
this.teacher = "Not Set";
studentList = new ArrayList<Student>();
}
/**
* Constructor with parameters
* #param noOfStudents integer
* #param courseName String with the Course name
* #param teacher String with the teacher
*/
public Course(String courseName, String teacher, int noOfStudents){
this.courseName = courseName;
this.teacher = teacher;
noOfStudents = noOfStudents;
studentList = new ArrayList<Student>();
}
public static void addStudent(Student newStudent){
if(studentList.size()==noOfStudents){
System.out.println("The class is full, you cannot enrol.");
}
else {
studentList.add(newStudent);
}
}
public String toString() {
return "Course Name: " + this.courseName + " Teacher: " + this.teacher
+ " Number of Students: " + this.noOfStudents;
}
}
Student class:
public class Student {
private String name;
private int age;
public String gender = "na";
private String course;
private String phoneNo;
public static int instances = 0;
// Getters
public int getAge(){
return this.age;
}
public String getName(){
return this.name;
}
public String getCourse(){
return this.course;
}
public String getPhoneNo(){
return this.phoneNo;
}
// Setters
public void setAge(int age){
this.age = age;
}
public void setName(String name){
if (JavaLecture3.DEBUG > 3) System.out.println("In Student.setName. Name = "+ name);
this.name = name;
}
public void setCourse(String course){
this.course = course;
}
public void setPhoneNo(String phoneNo){
this.phoneNo = phoneNo;
}
/**
* Default constructor. Populates name,age,gender,course and phone Number
* with defaults
*/
public Student(){
instances++;
this.age = 18;
this.name = "Not Set";
this.gender = "Not Set";
this.course = "Not Set";
this.phoneNo = "Not Set";
}
/**
* Constructor with parameters
* #param age integer
* #param name String with the name
* #param course String with course name
* #param phoneNo String with phone number
*/
public Student(int age, String name, String course, String phoneNo){
this.age = age;
this.name = name;
this.course = course;
this.phoneNo = phoneNo;
}
/**
* Gender constructor
* #param gender
*/
public Student(String gender){
this(); // Must be the first line!
this.gender = gender;
}
protected void finalize() throws Throwable{
//do finalization here
instances--;
super.finalize(); //not necessary if extending Object.
}
public String toString (){
return "Name: " + this.name + " Age: " + this.age + " Gender: "
+ this.gender + " Course: " + this.course + " Phone number: "
+ this.phoneNo;
}
}
Reference:
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html?is-external=true
Course.getNoOfStudents should just return studentList.size(). No need to maintain a separate variable.
To print a list of students (from Course):
for(int i=0;i<studentList.size();i++) System.out.println(studentList.get(i));
Since you initialized the array list in the Course class, you should add the students to it. You should create a method in Course that adds an object to the array list such as:
public void addStudent(Student s){
studentList.add(s);
noOfStudents++;
}
To add multiple students:
public void addStudents(Student[] students){
for(int i = 0; i < students.length; i++){
studentList.add(students[i]);
}
}
You're almost there, just use the .add method made for you in the array list.
public class JavaLecture3 {
public static final int DEBUG = 0;
public static void main(String [] args){
Student student = new Student(); // Calling default constructor here.
Course course = new Course();
student = new Student(21, "Joe", "CSE", "07447832342");
course = new Course("CSE", "Tom", 5);
course.addStudent(student);
System.out.println("Course Information: ");
System.out.println("-------------------");
System.out.println(course);
System.out.println();
System.out.println("Student contains: "); // calls student.toString());
System.out.println("-------------------");
System.out.println(student);
}
}
public class Course {
List<Student> studentList;
private String courseName;
private String teacher;
private int noOfStudents;
// Getters
public String getCourseName() {
return this.courseName;
}
public int getNoOfStudents() {
return this.noOfStudents;
}
public String getTeacher() {
return this.teacher;
}
// Setters
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public void setNoOfStudents(int noOfStudents) {
this.noOfStudents = noOfStudents;
}
public void setTeacher(String teacher) {
this.teacher = teacher;
}
/**
* Default constructor. Populates course name, number of students with
* defaults
*
*/
public Course() {
this.noOfStudents = 0;
this.courseName = "Not Set";
this.teacher = "Not Set";
studentList = new ArrayList<Student>();
}
/**
* Constructor with parameters
*
* #param noOfStudents
* integer
* #param courseName
* String with the Course name
* #param teacher
* String with the teacher
*/
public Course(String courseName, String teacher, int noOfStudents) {
this.courseName = courseName;
this.teacher = teacher;
this.noOfStudents = noOfStudents;
studentList = new ArrayList<Student>();
}
public void addStudent(Student newStudent) {
if (studentList.size() == noOfStudents) {
System.out.println("The class is full, you cannot enrol.");
} else {
studentList.add(newStudent);
}
}
#Override
public String toString() {
return "Course Name: " + this.courseName + " Teacher: " + this.teacher
+ " Number of Students: " + studentList.size();
}
}
public class Student {
private String name;
private int age;
public String gender = "na";
private String course;
private String phoneNo;
public static int instances = 0;
// Getters
public int getAge() {
return this.age;
}
public String getName() {
return this.name;
}
public String getCourse() {
return this.course;
}
public String getPhoneNo() {
return this.phoneNo;
}
// Setters
public void setAge(int age) {
this.age = age;
}
public void setName(String name) {
if (JavaLecture3.DEBUG > 3)
System.out.println("In Student.setName. Name = " + name);
this.name = name;
}
public void setCourse(String course) {
this.course = course;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
/**
* Default constructor. Populates name,age,gender,course and phone Number
* with defaults
*/
public Student() {
instances++;
this.age = 18;
this.name = "Not Set";
this.gender = "Not Set";
this.course = "Not Set";
this.phoneNo = "Not Set";
}
/**
* Constructor with parameters
*
* #param age
* integer
* #param name
* String with the name
* #param course
* String with course name
* #param phoneNo
* String with phone number
*/
public Student(int age, String name, String course, String phoneNo) {
this.age = age;
this.name = name;
this.course = course;
this.phoneNo = phoneNo;
}
/**
* Gender constructor
*
* #param gender
*/
public Student(String gender) {
this(); // Must be the first line!
this.gender = gender;
}
protected void finalize() throws Throwable {
// do finalization here
instances--;
super.finalize(); // not necessary if extending Object.
}
public String toString() {
return "Name: " + this.name + " Age: " + this.age + " Gender: "
+ this.gender + " Course: " + this.course + " Phone number: "
+ this.phoneNo;
}
}
public class JavaLecture3 {
public static final int DEBUG = 0;
public static void main(String [] args){
//Create course object
Course course = new Course("CSE", "Tom", 5);
Scanner scanner = new Scanner(System.in);
String cmd = "Yes";
while(cmd.equals("Yes")){
Student student = new Student();
System.out.print("Enter a new student? ");
cmd = scanner.next();
if (cmd.equals("Yes")){
//Read student name
System.out.print("Enter a student name: ");
String name = scanner.next();
student.setName(name);
//Read student Age
System.out.print("Enter a student age: ");
int age = scanner.nextInt();
student.setAge(age);
//Read student Course
System.out.print("Enter a student course: ");
String stdent_course = scanner.next();
student.setCourse(stdent_course);
//register the student to the class
course.addStudent(student);
}
}
scanner.close();
System.out.println("Course Information: ");
System.out.println("-------------------");
System.out.println(course.toString());
System.out.println();
}
}
I reworked a bit your toString() method from Course class. This should print the list of students attending a class.
public String toString (){
String ret_value = "Name: " + this.name + " Age: " + this.age + " Gender: "
+ this.gender + " Course: " + this.course + " Phone number: "
+ this.phoneNo + " Students attending this course:";
for (Student student: studentList) {
ret_value = ret_value + " " + Student.getName();
}
return ret_value;
}
Related
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 3 years ago.
string value is not displaying all though told the computer to display Please help
import java.util.Scanner;
class Author
{
private String name;
private String email;
private char gender;
public Author (String name, String email, char gender) {
this.name=name;
this.setEmail(email);
this.gender=gender;
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #return the email
*/
public String getEmail() {
return email;
}
/**
* #param email the email to set
*/
public void setEmail(String email) {
this.email = email;
}
/**
* #return the gender
*/
public char getGender() {
return gender;
}
#Override
public String toString() {
return "Author [name=" + name + ", email=" + email + ", gender=" + gender + "]";
}
}
class Book
{
private String Name;
Author auth;
private double price;
private int qty;
/**
* #param name
* #param auth
* #param price
*/
public Book(String name, Author auth, double price) {
super();
Name = name;
this.auth = auth;
this.price = price;
}
/**
* #param name
* #param auth
* #param price
* #param qty
*/
public Book(String name, Author auth, double price, int qty) {
super();
Name = name;
this.auth = auth;
this.price = price;
this.qty = qty;
}
public String getName() {
return Name;
}
public Author getAuth() {
return auth;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
#Override
public String toString() {
return "Book [Name=" + Name + ", auth=" + auth + ", price=" + price + ", qty=" + qty + "]";
}
}
class Student
{
private String Name;
private int roll;
date issueDate;
date returnDate;
/**
* #param name
* #param roll
* #param issueDate``
* #param returnDate
*/
public Student(String name, int roll, date issueDate, date returnDate) {
super();
Name = name;
this.roll = roll;
this.issueDate = issueDate;
this.returnDate = returnDate;
}
public String getName() {
return Name;
}
public int getRoll() {
return roll;
}
public date getIssueDate() {
return issueDate;
}
public date getReturnDate() {
return returnDate;
}
public void setReturnDate(date returnDate) {
this.returnDate = returnDate;
}
}
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
Author ahTeck=null;
System.out.println("How many Book are there in library ?");
int n=sc.nextInt();
Book []ob=new Book[n];
for(int i=0;i<n;++i)
{ System.out.println("Author's name");
String s=sc.nextLine();
sc.nextLine();
System.out.println("Author's Email Id");
String s1=sc.nextLine();
System.out.println("gender:");
char c = sc.next(".").charAt(0);
sc.nextLine();
System.out.println("Book Name:");
String b=sc.nextLine();
System.out.println("Book price:");
double price=sc.nextInt();
System.out.println("Book quantity");
int q=sc.nextInt();
ob[i]=new Book(b, new Author(s, s1, c),price,q);
System.out.println(ob[i]);
}
}
}
the question is there in
https://www.ntu.edu.sg/home/ehchua/programming/java/J3f_OOPExercises.html
Output is coming like
Book [Name=g, auth=Author [name=, email=e, gender=m], price=6.0, qty=6]
the displaying of author name is skipped
Ah yes. The ol' Scanneroo.
Right after entering the integer at the top, call sc.nextLine();
int n = sc.nextInt();
sc.nextLine();
Actually, you don't even have to call sc.nextLine() after entering a string or character. The thing is, when you enter a number, you hit the enter key as well. The Scanner class regards it as another token when you use nextInt(), so the number gets stored correctly, but the enter key \n is regarded as another token.
So when you call nextLine() after entering the number, the system sees that there is already a token remaining in the Scanner object, so it takes '\n' as its input. Thus, the name actually stores "\n", which is empty.
My problem is that I will be giving a file with student information: name, age, and GPA. I then have to turn each data element into a separate array. I then have to sort GPA into descending order, while keeping name and age with the corresponding GPA, and then print it out with "Name Age GPA" heading.
Check below code to sort data based on GPA. However you will have to include relevant code for file reading.
Student.java (POJO)
public class Student {
String name;
int age;
double GPA;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getGPA() {
return GPA;
}
public void setGPA(double gPA) {
GPA = gPA;
}
public Student(String name, int age, double gPA) {
super();
this.name = name;
this.age = age;
GPA = gPA;
}
#Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", GPA=" + GPA + "]";
}
}
StudentSorter.java
import java.util.Comparator;
public class StudentSorter implements Comparator<Student> {
#Override
public int compare(Student o1, Student o2) {
if(o1.getGPA() < o2.getGPA()) return 1;
if(o1.getGPA() > o2.getGPA()) return -1;
else return 0;
}
}
Tester.java
public class Tester {
public static void main(String[] args) {
Student s1 = new Student("A",14,7.9);
Student s2 = new Student("B",17,8.2);
Student s3 = new Student("C",20,7.0);
Student s4 = new Student("D",15,6.9);
Student s5 = new Student("E",14,9.1);
List<Student> list = new ArrayList<>();
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);
list.add(s5);
StudentSorter ss = new StudentSorter();
Collections.sort(list, ss);
System.out.println(list.toString());
}
}
I am trying to create an array of students which will contain 3 different types of students and each of the students will have 3 variables name, and 2 grades.
This is what I have done so far, and it gives me the following error cannot find symbol.
Main class:
public class JavaLab5 {
public static final int DEBUG = 0;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Student s[] = new Student[10];
s[0] = new MathStudent(Smith,14,15);
s[1] = new MathStudent(Jack,16,19);
s[2] = new MathStudent(Victor,18,21);
s[3] = new MathStudent(Mike,23,28);
s[4] = new ScienceStudent(Dave,32,25);
s[5] = new ScienceStudent(Oscar,28,56);
s[6] = new ScienceStudent(Peter,29,28);
s[7] = new ComputerStudent(Philip,25,38);
s[8] = new ComputerStudent(Shaun,34,39);
s[9] = new ComputerStudent(Scott,45,56);
for (int loop = 0; loop < 10; loop++) {
System.out.println(s[loop].getSubjects());
System.out.print(loop + " >>" + s[loop]);
}
}
}
This is the Student class:
public class Student {
private String name;
//private int age;
//public String gender = "na";
public static int instances = 0;
// Getters
//public int getAge() {
//return this.age;
//}
public String getName() {
return this.name;
}
// Setters
//public void setAge(int age) {
//this.age = age;
//}
public void setName(String name) {
if (JavaLab5.DEBUG > 3) System.out.println("In Student.setName. Name = "+ name);
this.name = name;
}
/**
* Default constructor. Populates name,age and gender
* with defaults
*/
public Student() {
instances++;
//this.age = 18;
this.name = "Not Set";
//this.gender = "Not Set";
}
/**
* Constructor with parameters
* #param age integer
* #param name String with the name
*/
public Student(String name) {
//this.age = age;
this.name = name;
}
/**
* Gender constructor
* #param gender
*/
//public Student(String gender) {
//this(); // Must be the first line!
//this.gender = gender;
//}
/**
* Destructor
* #throws Throwable
*/
protected void finalize() throws Throwable {
//do finalization here
instances--;
super.finalize(); //not necessary if extending Object.
}
public String toString () {
return "Name: " + this.name; //+ " Age: " + this.age + " Gender: "
//+ this.gender;
}
public String getSubjects() {
return this.getSubjects();
}
}
and this is the MathStudent class which inherits from the Student class:
public class MathStudent extends Student {
private float algebraGrade;
private float calculusGrade;
/**
* Default constructor
* #param name
* #param algebraGrade
* #param calculusGrade
*/
public MathStudent(String name, float algebraGrade, float calculusGrade) {
super();
this.algebraGrade = algebraGrade;
this.calculusGrade = calculusGrade;
}
public MathStudent() {
super();
algebraGrade = 6;
calculusGrade = 4;
}
// Getters
public void setAlgebraGrade(float algebraGrade){
this.algebraGrade = algebraGrade;
}
public void setCalculusGrade(float calculusGrade){
this.calculusGrade = calculusGrade;
}
// Setters
public float getAlgebraGrade() {
return this.algebraGrade;
}
public float getCalculusGrade() {
return this.calculusGrade;
}
/**
* Display information about the subject
* #return
*/
#Override
public String getSubjects(){
return(" Math Student >> " + "Algebra Grade: " + algebraGrade
+ " Calculus Grade: " + calculusGrade);
}
}
Check how you instantiate students, i.e.
new MathStudent(Smith,14,15);
The name should be in quotes like "Smith"
new MathStudent("Smith",14,15);
Otherwise Smith will be interpreted as variable and this one is not defined.
/* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication3;
class Employee {
private String name;
private String address;
private int number;
public Employee(Employee emp) {
System.out.println("Constructing an Employee");
this.name = emp.name;
this.address = emp.address;
this.number = emp.number;
}
/*public Employee(String name, String address, int number) {
System.out.println("Constructing an Employee");
this.name = name;
this.address = address;
this.number = number;
}*/
public void mailCheck() {
System.out.println("Mailing a check to " + this.name
+ " " + this.address);
}
public String toString() {
return name + " " + address + " " + number;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public void setAddress(String newAddress) {
address = newAddress;
}
public int getNumber() {
return number;
}
}
class Salary extends Employee {
private double salary; //Annual salary
public Salary(Salary obj) {
super(obj);
setSalary(obj.salary);
}
/*public Salary(String name, String address, int number, double Salary) {
super(name, address, number);
setSalary(Salary);
}*/
public void mailCheck() {
System.out.println("Within mailCheck of Salary class ");
System.out.println("Mailing check to " + getName()
+ " with salary " + salary);
}
public double getSalary() {
return salary;
}
public void setSalary(double newSalary) {
if (newSalary >= 0.0) {
salary = newSalary;
}
}
public double computePay() {
System.out.println("Computing salary pay for " + getName());
return salary / 52;
}
}
public class JavaApplication3 {
public static void main(String[] args) {
Salary s = new Salary("Mohd Mohtashim", "Ambehta,UP", 3, 2000.00); // error why
System.out.println("Call mailCheck using Salary reference --");
s.mailCheck();
}
}
If we removed the comments from the constructor, then it will be okay. Why?
Salary s = new Salary("Mohd Mohtashim", "Ambehta,UP", 3, 2000.00); you're calling a constructor that takes multiple parameters but it doesn't exist since you've commented it out .
i have problem with printing the array after reading it. After printing, the address of memory is printed, not value of the array. What can i do for that ?
public class MyClass
{
Student St = new Student();
Student[]Array1 = new Student[10];
void AddList()
{
Scanner Scan = new Scanner(System.in);
for (int i=0; i<Array1.length & i<ArrayF1.length; i++)
{
System.out.println("Enter Student NAME Number " + (i+1) + ":");
Array1[i] = new Student();
Array1[i].setName(Scan.next());
//System.out.println("Enter Student MARK Number " + (i+1) + ":");
//St.setMark(Scan.nextFloat());
}
}
this is my print method. The result of print is like this
(studentproject.Student#1a758cb)
void PrintList()
{
for (int i=0; i<Array1.length; i++)
{
System.out.println(Array1[i]);
}
}
this is my Student Class that i have all my setter and getter method on that ... So i have 3 Class how can i work with this 3 class and in one of them get the data and in another print the Mark data and in third class print the Student Name data ... how can i do that ... i do some code but i dont know is it correct or not ... thanks for your help ...
public class Student
{
private String Name;
private float Mark;
/**
* #return the Name
*/
public String getName() {
return Name;
}
/**
* #param Name the Name to set
*/
public void setName(String Name) {
this.Name = Name;
}
/**
* #return the Mark
*/
public float getMark() {
return Mark;
}
/**
* #param Mark the Mark to set
*/
public void setMark(float Mark) {
this.Mark = Mark;
}
}
Just override the toString() method in Student class, and return the appropriate string you want to get printed when you print an instance.
It may look like: -
#Override
public String toString() {
return "Name: " + studentName;
}
Currently, the default implementation of toString() method of Object class is invoked, and what you are seeing is the format returned from that method, which is of the form - Type#hashCode
Here I've added some stuff how toString() method can be override
public class Student {
private String name;
private int id;
float mark;
public Student() {
}
public Student(String name, int id) {
this.name = name;
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getMark() {
return mark;
}
public void setMark(float mark) {
this.mark = mark;
}
#Override
public String toString() {
return "Student[ID:" + id + ",Name:" + name + ",Mark:"+mark+"]";
}
public void printStudentInfo() {
// print all the details of student
}
public static void main(String[] args) {
Student[] students = new Student[10];
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < students.length; i++) {
System.out.println("Enter Student Name " + (i + 1) + ":");
String name = scanner.nextLine();
Student student = new Student(name, i + 1);
System.out.println("Enter Student MARK Number " + (i + 1) + ":");
float mark = scanner.nextFloat();
student.setMark(mark);
students[i]=student;
}
for(Student student:students) {
// by default toStirng method is called
System.out.println(student);
//or you can call like
//student.printStudentInfo();
}
}
}