Can I use arrays in Java to store linked data - java

I have a project where I want to store data about students(name,age,registration number etc)
I don't know how else to store the data so I thought arrays would be worthwhile. How would I link data from the name array to the age array????

In first, create a Student object like this:
public class Student {
private final String name;
private final int age;
private final int registrationNumber;
public Student(String name, int age, int registrationNumber) {
this.name = name;
this.age = age;
this.registrationNumber = registrationNumber;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public int getRegistrationNumber() {
return registrationNumber;
}
}
And after, you can create a list of Student who provide an in memory storage for your students:
List<Student> students = new ArrayList<>();
students.add(new Student("Valentin", 23, 123456));
students.add(new Student("Alexander", 14, 82835));
I hope this gonna help you.

Related

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

Creating this constructor class with parameters

I'm new to JAVA and I struggled with this question which is very unclear to me. I'm politely asking if someone could discussing it with me or teach me how to answer it? Thank you.
Question:
A Company class holds an array of employees and its constructor takes in as parameters 4 arrays of the same length. The first array is an array of String being the names of employees; the second array is an array of String being the respective addresses; the third array is an array of int being the respective employee numbers; the fourth array is an array of double being the respective salaries.
I know how to do the public constructor one but I am unsure about the constructor of the class Company.
Your help is very valuable to me. Thank you in advance.
Feels like a very simple class structure.
public class Company {
Employee[] employees;
public Company (String[] names, String[] addresses, int[] ids, double[] salaries) {
employees = new Employee[names.length];
for (int i = 0; i < employee.length; i++) {
employees[i] = new Employee (names[i], addresses[i], ids[i], salaries[i]);
}
}
static class Employee {
String name;
String address;
int id;
double salary;
Employee (String name, String address, int id, double salary) {
this.name = name;
this.address = address;
this.id = id;
this.salary = salary;
}
}
}
Please delete question if this is a school assignment and you are using stackoverflow to cheat.
public Company(String[] names, String[] addresses, int[] employeeNumbers, double[] salaries) {
}
A better design would be
public Company(Employee[] employees) {
}
and have an employee class
public class Employee {
private String name;
private String address;
private int employeeNumber;
private double salary; // you may not want to use this in production
public Employee(String name, String address, int employeeNumber, double salary) {
}
// constructors, getters and setters, etc
}
According to #Kayaman comment seems you already have an employee class but for some reason you don't want to use the first constructor that takes an array of employees instead of 4 arrays. You want to use the first constructor with the 4 array parameters and construct array objects from the parameters. That's actually bad programming. It makes you code look dirty.
If it's a school assignment and you are required to do it that way, I'm guessing the instructor probably just wants you to learn something out of it. But code like that should not be written in production.
Anyways, here is the solution you might be looking for
public class Company {
private Employee[] employees;
public Company(String[] names, String[] addresses, int[] employeeNumbers, double[] salaries) {
employees = new Employees[names.length]; // assuming all arrays are of the same length
for (int i = 0;i < employees.length;i++) {
employees[i] = new Employee(names[i], addresses[i], employeeNumbers[i], salaries[i]);
}
}
}
import java.util.ArrayList;
import java.util.Collections;
public Class Company
{
ArrayList<Employee> employees = new ArrayList<Employee>();
public Company(Employee[] newEmployees)
{
employees.addAll(newEmployees);
}
}
public Class Employee
{
public String Name;
public String Address;
public Int Id;
public Double Salary;
public Employee(string name, string address, int id, double salary)
{
this.Name = name;
this.Address = address;
this.Salary = salary;
this.Id = id;
}
}
To create a new company:
Employee[] e = {
new Employee("Bob", "Bobs address", 1, 50000),
new Employee("Jane", "Janes address", 3, 85000)
}
Company c = new Company(e);

Java class setter not setting correct value to class field.

I have a simple java program I and I cannot figure out why the setter for a class will not set the correct value.
I have a class Employee, a class Department, a class Company. Once I am able to set correct values to the fields of an Employee instance I will then store that employee in a arraylist of employees in an instance of Department(arrayList field).
The class called Employee. It has four fields, String fName, String lName, int age, String department. I am able to set fName and lName though age is always set to 0 and department is always set to null.
Here is the code for the employee class:
public class Employee {
private String fName;
private String lName;
private String department;
private int age;
//getters and setters for the private fields of the Employee class
public void setAge(int num){
num = age;
}
public int getAge(){
return age;
}
public void setDepartment(String dep){
dep = department;
}
public String getDepartment(){
return department;
}
public void setfName(String afName){
fName = afName;
}
public String getfName(){
return fName;
}
public void setlName(String alName){
lName = alName;
}
public String getlName(){
return lName;
}
}
Here is the code for a method called addEmployee:
public void AddEmployee(Department depInstance){
String firstName = JOptionPane.showInputDialog("Enter employee First name");
String lastName = JOptionPane.showInputDialog("Enter employee last name");
int empAge = Integer.parseInt(JOptionPane.showInputDialog("Enter employee age"));
String empDep = JOptionPane.showInputDialog("Enter employee department");
Employee employeeToAdd = new Employee();
employeeToAdd.setfName(firstName);
employeeToAdd.setlName(lastName);
employeeToAdd.setAge(empAge);
employeeToAdd.setDepartment(empDep);
//test input and variable setting
System.out.println("--------Inputs------");
varTester(firstName,lastName,empAge,empDep);
System.out.println("--------Recorded Vals------");
varTester(employeeToAdd.getfName(), employeeToAdd.getlName(),employeeToAdd.getAge(),employeeToAdd.getDepartment());
public static void varTester(String empfName, String emplName, int empAge, String empDep){
System.out.println(empfName);
System.out.println(emplName);
System.out.println(empAge);
System.out.println(empDep);
}
}
This is the output from the test method varTester():
--------Inputs------
Somefirstname
Somelastname
32
Accounting
--------Recorded Vals------
Somefirstname
Somelastname
0
null
I test the values received from the showInputDialog's and it is the correct values I want to store int the class instance fields of employeeToAdd though only the first and last name values are set and not the age or department. Can someone point me in the right direction. Thank you.
You got the setter backwards. It should be :
public void setAge(int num){
age = num;
}
You have the same error in setDepartment.
You are supposed to assign to the member variable, not to the argument of the setter method.
Your setter sets the argument not the private field.
public void setAge(int num){
num = age;
}
public void setDepartment(String dep){
dep = department;
}
Change it to:
public void setAge(int num){
age = num;
}
public void setDepartment(String dep){
department = dep;
}
It should be:
public void setAge(int num){
age = num;
}
public void setDepartment(String dep){
department = dep;
}

Save custom array of objects to file and read again in java?

I would like to save an array of objects that is custom as a file and re-read it back as an array of objects on program start in java. If I could also save it as JSON, it would be nice. I have tried some common methods but I get a error saying that my array is not serialiazable.
class ArrayOfObjects {
public static void main (String[] args) throws Exception {
Students[] studentArray = new Students[3];
studentArray[0] = new Students();
studentArray[0].age = 18;
studentArray[0].name = "Jones";
studentArray[1] = new Students();
studentArray[1].age = 21;
studentArray[1].name = "David";
studentArray[2] = new Students();
studentArray[2].age = 15;
studentArray[2].name = "Jeremy";
}
}
class Students {
int age;
String name;
}
your class Students should implement Serialiazble
If you want to save it in standard output, Students must implement Serializable.
If you wan to save it as JSON, use Jackson (http://fasterxml.com/) and normalise it Java bean declaration to the class.
class Students implemenst Serializable {
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

How to create a roster of students in java

I have a homework assignment problem that looks like this:
(20 pts) Create a Student class with the following:
A private String variable named “name” to store the student’s name
A private integer variable named “UFID” that contains the unique ID number for this student
A private String variable named “DOB” to store the student’s date of birth
A private integer class variable named numberOfStudents that keeps track of the number of students that have been created so far
A public constructor Student(String name, int UFID, String dob)
Several public get/set methods for all the properties
getName/setName
getUFID/setUFID
getDob/setDob
Write a test program, roster.java, that keeps a list of current enrolled students. It should have methods to be able to enroll a new
student and drop an existing student.
I'm not asking anyone to do this assignment for me, I just really need some general guidance. I think I have the Student class pretty well made, but I can't tell exactly what the addStudent() and dropStudent() methods should do - should it add an element to an array or something or just increments the number of students? The code I have so far looks like this.
public class Student {
private String name;
private int UFID;
private String DOB;
private static int numberOfStudents;
public Student(String name, int UFID, String DOB) {
this.name = name;
this.UFID = UFID;
this.DOB = DOB;
}
public String getDOB() {
return DOB;
}
public void setDOB(String dOB) {
DOB = dOB;
}
public int getUFID() {
return UFID; }
public void setUFID(int uFID) {
UFID = uFID; }
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNumberOfStudents() {
return numberOfStudents;
}
public void setNumberOfStudents(int numberOfStudents) {
Student.numberOfStudents = numberOfStudents;
}
public static void addStudent(String name, int UFID, String DOB) {
numberOfStudents++;
}
public static void dropStudent(String name) {
numberOfStudents--;
}
}
Any guidance as I finish this up would be greatly appreciated.
The assignment writes itself: you need a Roster class that owns and maintains a collection of Students:
public class Roster {
private Set<Student> roster = new HashSet<Student>();
public void addStudent(Student s) { this.roster.add(s); }
public void removeStudent(Student s) { this.roster.remove(s); }
}

Categories