Display class objects from a class method - java

I've created class Person, which is extended by classes Student and Employee (which is extended by other Employee type classes). The person class looks like:
String name;
int ssn;
int age;
String gender;
String address;
String PNumber;
static int count;
//empty constructor
public Person(){
count++;
}
//print count
public static void printCount(){
System.out.println("The number of people is: "+ count);
}
//constructor with name
public Person(String name){
this.name = name;
count++;
}
/*constructor to create default person object*/
public Person(String name, int ssn, int age, String gender, String address, String PNumber)
{
this.name = name;
this.ssn = ssn;
this.age = age;
this.gender = gender;
this.address = address;
this.PNumber = PNumber;
count++;
}
I'm currently trying to create a method that will display all Persons if they're gender = "Male". I have:
//display Males
public void print(String gender){
if(this.gender.contentEquals(gender)){
//print out person objects that meet this if statement
}
}
I'm not sure how to refer to the objects (students and employees that are all persons) within the method to return them. And I also don't know how to refer to this method in the main method. I can't use Person.print, but if I use
Person james = new Person();
and then use
james.print("Males");
I'm only returning james (and the method doesn't make sense in that context).
Any help appreciated.

First, the print method should be made into a static method. It is independent of each individual Person object, so making it static will allow you to call it in the main method as
Person.print("Male");
To refer to Person objects in the print method, you will need to pass it a collection of Person objects as a parameter. You should keep all instances of Person in an array and pass that into the print method when you call it. Then the print method can be
public static void print(String gender, Person[] people) {
for(Person x : people)
if (x.gender.equals(gender))
//print the person
}
With this modification you should call it from the main method as
Person.print("Male", people);
where people is the array you keep all Person objects in.

Related

How do I let a user input data and create an object with input dialog?

These are my requirements:
Write a program (Person) that has the following attributes: name, adress, age.
Write four constructors
Write get set methods
Write a toString method.
Write a seperate program (TestClass) and let the user enter the name, adress and age in three different dialogboxes and then create an object of the class Person and store the data in this object.
In the same way, let the user create four more objects but use one of the constructors with each object.
View the data for each object through a dialog box, using the toString method.
That was my instructions and below is my code for the program(class) Person:
public class Person
{
private String name;
private String adress;
public int age;
public Person(String name, String adress, int age)
{
this.name=name;
this.adress=adress;
this.age=age;
}
public Person(String name, int age)
{
this.name=name;
this.age=age;
this.adress="";
}
public Person(String name, String adress)
{
this.name=name;
this.adress=adress;
this.age=0;
}
public Person(String name)
{
this.name=name;
this.adress="";
this.age=0;
}
public Person()
{
this.name="";
this.adress="";
this.age=0;
}
public void setName(String name)
{
this.name=name;
}
public void setAdress(String adress)
{
this.adress=adress;
}
public void setAge(int age)
{
this.age=age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public String getAdress()
{
return adress;
}
public String toString()
{
return " Name : " + name + " Age: " + age+ " " + " Adress: " + adress;
}
}
And hereeee is the code for my program TestClass. Look at the comments
import javax.swing.JOptionPane;
public class TestClass
{
public static void main(String[]args)
{
// 5. Write a seperate program (TestClass) and let the user enter the name, adress and age
int r1;
String name=JOptionPane.showInputDialog("Whats your name ?");
String adress=JOptionPane.showInputDialog("Whats your adress? ");
String sR1=JOptionPane.showInputDialog("What's your age? ");
r1=Integer.parseInt(sR1);
Person p1=new Forening(name, adress, r1);
JOptionPane.showMessageDialog(null,p1.toString());
// 6.let the user create four more objects but use one of the constructors with each object.
Person p3=new Person("Johanna", 2004);
JOptionPane.showMessageDialog(null,p3.toString());
Forening p4=new Person("John", "JavaScriptstreet 1");
JOptionPane.showMessageDialog(null,p4.toString());
Person p5=new Person("Sandra");
JOptionPane.showMessageDialog(null,p5.toString());
Obviously I'm not doing soooomething right!! It's the part where I'm supposed to let the user input data through dialog boxes and let the user create objects of the class to store the data and then show the data that I'm struggling with..

Add student to student ArrayList (java)

Before you read ahead, this is for my homework so the questions/answers are going to be specific.
I am writing some code that takes a student's name and adds it to the student ArrayList. I have a class for students and another class for a course (the course is where the add student and the ArrayList is ). The problem that I am having is that the code is restricting me from using some methods of the student class even though I have used them before. Also, the newly created student has to return the reference of the student, and if it fails it will return null. I have tried that but it has given me errors and I am unsure on how to incorporate the if-else function within the method.
Below is my code for the student class:
public class Student {
// instance fields
//class implementation
private String name;
private String surname;
private long studentId;
private String loginId;
private static int count = 10000001;
private double[] quizMarks; //declare as an array
//constuctors
public Student(String name, String surname) {
this.name = name;
this.surname = surname;
this.studentId = studentId;
quizMarks = new double[0];//initialize array
}
//accessors and mutator methods
//set student's name and surname. Changing student's name does not affect the students' loginID
public void Name(String name, String surname) {
}
//returns name and surname separated by comma (name, surname)
public String setName() {
return name + ", " + surname;
}
}
class for Course:
import java.util.ArrayList;
public class Course{
private ArrayList<Student> students;
ArrayList<Double> quiz;
public Course() {
students = new ArrayList<Student>();
quiz = new ArrayList<Double>();
}
Student addStudent (String name, String familyName){
students.add(setName(Name(name, familyName)));
return null;
}
Student deleteStudent(long studentId){
students.remove(studentId);
return null;
}
}
}
This,
students.add(setName(Name(name, familyName)));
is not correct. You don't want to add a String to stduents you want a Student. Like,
students.add(new Student(name, familyName));
import java.util.ArrayList;
public class Course{
// variables and constructors
Student addStudent (String name, String familyName){
students.setName(name, familyName);
return null;
}
Student deleteStudent(long studentId){
students.remove(studentId);
return null;
}
}
}
There exists no Add or remove method in class Student so either you can add them in your format or correct that format.
public class Student {
// variables
// constuctors
public Student(String name, String surname) {
this.name = name;
this.surname = surname;
this.studentId = studentId;
quizMarks = new double[0];//initialize array
}
public Student remove(Student obj) {
obj = null; //Destroying the reference
}
public void Name(String name, String surname) {
}
//returns name and surname separated by comma (name, surname)
public String setName() {
return name + ", " + surname;
}
}

If I create an array of the parental class, how do I access a method from the sub class through the array object?

I have a program I am working with to help me practice my coding skills. The program has the following scenario: there is a classroom of 20 students, where the record is taken of the students' names, surnames, and age. Half of these students take part in the school's athletics. Here, record is kept of their races that they have done and the ones they've won.
In this program, I have three classes:
runStudents - class with main method
Students (String name, String surname, int age) - parental class
AthleticStudents (String name, String surname, int age, int races, int victories) - sub class
The user should be able to add another race (and win) to the object. As seen by the code provided, an Array is created to store the 20 Students objects. I have to be able to access a method to alter the object in the array, but this method is not in the parental class (the class the objects are created from.
public class Students
{
private String name;
private String surname;
private int age;
public Students()
{
}
public Students(String name, String surname, int age)
{
this.name = name;
this.surname = surname;
this.age = age;
}
public String getName()
{
return this.name;
}
public String getSurname()
{
return this.surname;
}
public double getAge()
{
return this.age;
}
public void setName(String name)
{
this.name = name;
}
public void setSurname(String surname)
{
this.surname = surname;
}
public void setAge(int age)
{
this.age = age;
}
public String toString()
{
return String.format("name\t\t: %s\nsurname\t\t: %s\nage\t\t: %s",
this.name, this.surname, this.age);
}
}
public class AthleticStudents extends Students
{
private int races;
private int victories;
public AthleticStudents()
{
}
public AthleticStudents(String name, String surname, int age, int
races, int victories)
{
super(name, surname, age);
this.races = races;
this.victories = victories;
}
public int getRaces()
{
return this.races;
}
public int getVictories()
{
return this.victories;
}
public void setRaces(int races)
{
this.races = races;
}
public void setVictories(int victories)
{
this.victories = victories;
}
public void anotherRace()
{
this.races = this.races + 1;
}
public void anotherWin()
{
this.victories = this.victories + 1;
}
public String toString()
{
return super.toString() + String.format("\nnumber of races\t:
%s\nnumber of wins\t: %s", this.races, this.victories);
}
}
public class runStudents
{
public static void main(String[]args)
{
Students[] myStudents = new Students[20];
myStudents[0] = new Students("John", "Richards", 15);
myStudents[1] = new AthleticStudents("Eva", "Grey", 14, 3, 1);
myStudents[2] = new Students("Lena", "Brie", 15);
for (int i = 0; i < 3; i++)
System.out.println(myStudents[i].toString() + "\n\n");
}
}
I want to be able to do the following:
AthleticStudents[1].anotherRace();
but cannot do so as the array object is derived from the parental class, and I declared the method in the sub class. How can I link the two?
I assume that you create an array of the parent class instances. Just cast the instance this way (you better check whether the element is the instance of a subclass):
if (AthleticStudents[1] instanceof AthleticStudents)
((AthleticStudents) AthleticStudents[1]).anotherRace();
I'm not sure if this is exactly what you're looking for but it worked well for me. Instead of trying to access AthleticStudents method anotherRace() like that, try this in your main method.
Students[] myStudents = new Students[20];
myStudents[0] = new Students("John", "Richards", 15);
myStudents[1] = new AthleticStudents("Eva", "Grey", 14, 3, 1);
myStudents[2] = new Students("Lena", "Brie", 15);
AthleticStudents addRace= (AthleticStudents)myStudents[1];
addRace.anotherRace(); //This will increment Eva's race count to 4
for (int i = 0; i < 3; i++)
System.out.println(myStudents[i].toString() + "\n\n");
All I did was cast the element into an object AthleticStudents named 'addRace'. By casting myStudents[1] to this new object you are able to access all of AthleticStudents methods.
I just saw the other answer posted which works just as well!
Hope this helps!
I’m not sure that i understand your question, because you are a bit inconsistent with your capitalization. runStudents is a class, while AthleticStudents is both a class and an array. But i’ll try.
IF i did understand your question, you have an array Student[] studentArray. Some Student objects in studentArray are AthleticStudents, others are not. You have a specific AthleticStudent eva which is in studentArray[] having let’s say index 1, and you want to add to her anotherRace(). Your call studentArray[1].anotherRace does not compile because the compiler treats that element as a Student and not as a AthleticStudent.
The trick is to cast the element to AthleticStudent. I omit the test of the element of being really an AthleticStudent; you will have to do that test in your code.
((AthleticStudent) studentArray[1]).anotherRace();

Objected Oriented Programming- How to use the toString() method and format()?

I have just started doing object oriented programming as part of my course, but I am struggling with it, specifically the toString method in a Person Class. I need to write a toString() method to display the contents of instance variables.
I need to by sample print out:
Person[forName=joe, surname= smith, age= 25, height= 1.57, gender= male]
I also need to format it like this using the format method:
smith joe 25 1.57 male
davis sian 18 1.73 female
*** *** *** *** ***
I havent written a tester yet, but here is what I have written so far for the class and now I'm stuck, I'm not even sure if I am getting the toString statement wrong. I am using netBeans for this:
public class Person
{
private String surname;
private String forname;
private int age;
private double height;
private String gender;
public String toString()
{
return getClass().getName() + "[surname= " + surname + " forname= " + forname + " age= " + age + " height= " + height + " gender " + gender + "]";
}
}
What I need to do is make a class called Person that I can test. It needs to be able to hold the five variables above (surname etc) for different people. I need to be able to print out each of the instance variables with a toString() method and to use a format() method to produce a string with formatting infomation in order for the string printed out by the toString() method to be formatted like the second quotation.
Am I on the right track and regardless, how can I work through this?
EDIT: I have looked at the Person Class and have done what I can with it, does it seem decent enough? I am going to try and get a PersonTester together.
public class Person
{
private String surName;
private String forName;
private int age;
private double height;
private String gender;
#Override
public String toString()
{
return getClass().getName() + "[surName= " + surName + " forName= " + forName + " age= " + age + " height= " + height + " gender " + gender + "]";
}
public void format()
{
System.out.format("%10s%10s%10d%10f%10s", "surName", "forName", age, height, "gender");
}
public String getSurName()
{
return surName;
}
public String getForName()
{
return forName;
}
public int getAge()
{
return age;
}
public double getHeight()
{
return height;
}
public String getGender()
{
return gender;
}
public void setSurName(String surName)
{
this.surName = surName;
}
public void setForName(String forName)
{
this.forName = surName;
}
public void setAge(int age)
{
this.age = age;
}
public void setHeight(double height)
{
this.height = height;
}
public void setGender(String height)
{
this.gender = gender;
}
}
EDIT 2: Started on a class Tester, but I am running into errors again about the setter's not having a ; and not being a statement.
Here's the tester so far:
public class PersonTester
{
public static void main(String[] args)
{
System.out.println("PersonClassTester");
System.out.println("*****************");
System.out.println("");
Person joeSmith = new Person();
String "smith" = joeSmith.setSurName();
String "joe" = joeSmith.setForName();
int 25 = joeSmith.setAge();
double 1.57 = joeSmith.setHeight();
String "male" = joeSmith.setGender();
joeSmith.toString();
joeSmith.format();
}
}
First of all you have to noticed that every object you create extends class Object. This Object class contains methods like toString, equals, hashCode...
your object have also this methods(inherited from Object). When you override (you should annotate this method with #Override) for eg. toString you will always use this toString method instead of inherited one. Its called polymorphism. Your toString method looks fine. In your main method you should use some kind of loop through all Persons and there format the output from toString method.
You have error in your code
public String toString(); {
remove the ; after ()
public class Main {
public static void main(String[] args) {
Person a = new Person("smith", "joe", 25, 1.57, "male");
Person b = new Person("davis", "sian", 18, 1.73, "female");
List<Person> persons = new ArrayList<Person>();
persons.add(a);
persons.add(b);
for(Person p : persons){
System.out.format("%s %s %s %d %.2f %s", p.getClass().getName(), p.getSurname(), p.getForname(), p.getAge(), p.getHeight(), p.getGender());
System.out.println();
}
}
}
If you call this
System.out.println(p.toString());
than you ll get your person via toString method.
I just edit your Person class and add constructor and geters + seters
public Person(String surname, String forname, int age, double height,
String gender) {
super();
this.surname = surname;
this.forname = forname;
this.age = age;
this.height = height;
this.gender = gender;
}
Here is geter and seter sample.
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
As already mentioned your toString() is fine.
Please note that the toString() method and the format() method are IMO supposed to work independently as they do serve different purposes.
I suggest to put the format method not in the person class (or at least make it static method). This is because a single Person instance has not enough information for it to be printed in the table format. It at least needs to know the column widths. Otherwise you could end up with something like this:
smith joe 25 1.57 male
someVeryLongFirstName sian 18 1.73 female
*** *** *** *** ***
So the format method should take a list of persons that should be printed out and then first calculate the column widths. After this is done you then just pad the property value to the column width and print this out.
You are on the right track:
Inside of the Person class you need to add public methods for each private variable to set the data:
public void setAge(int age) {
this.age = age;
}
Then you can create a Person object in your main class and set his age:
public class Main {
public static void main(String[] args) {
Person p = new Person();
p.setAge(15);
}
}
As an alternative, you can use a constructor inside of your Person class to set your object's variables:
public Person(String surname, int age) {
this.surname = surname;
this.age = age;
}
And create the object in the main method like this:
Person p = new Person("Nillas", 25);
You can always run your toString() method in the main class after you've created the object and see the result:
System.out.println(p.toString());
Hope this helps, good luck!

calling out the constructor and assigning values to it from a scanner method

i was trying to make a program that asks the user to create a person or a group of persons and assign names and age to them. So I made a constructor "Try" and a method "AskUser".in AskUser() I use a do/while loop where user is asked to input a name, an age and if he likes to create another person. Now how do I take the input data each time the loop runs, and send it to constructor to create new objects with it? And how these new objects will be called?
import java.util.Scanner;
public class Try{
static String name;
static int age;
static Scanner a = new Scanner(System.in);
static Scanner b = new Scanner(System.in);
static Scanner c = new Scanner(System.in);
public Try(String name, int age){
this.name=name;
this.age= age;
System.out.println("this is "+name+", and he is "+age+" old.");
}
public static void AskUSer(){
int x=0;
do {System.out.print("what's the name of the person ?");
name= a.nextLine();
System.out.print("how old is he? ");
age= b.nextInt();
System.out.print("would u like to creat another person ");
String yes = c.nextLine();
if(!(yes.equals("yes"))){x++;}
} while(x==0);
}
public static void main (String[] args){
AskUSer();
System.out.print(age+ " "+ name);
}
}
You can construct the new object in AskUSer and return it as return value. So the code would look like:
public static YourObject AskUSer() {
...
}
aside from how you read from the user ,
it will be appropriate to make a class..
something like :
class Person {
private String name;
private int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return this.name;
}
public int getAge() {
return this.age;
}
}
and before entering the loop
you could use an ArrayList to hold people
ArrayList<Person> people = new ArrayList<Person>();
and each time you read the inputs .. instantiate a Person object and add it to the ArrayList
something like :
Person pr=new Person(name,age);
people.add(pr);

Categories