Creating methods and objects - java

Hello all so I was given this Driver class and was told to make classes to get the driver class working properly. For the most part I think im on the right track but then again im not completely sure because I am new to java. I am getting 2 compiling errors because I have not added a add(temp) method. to be honest im not sure what class to put the method into. for now I have it in the Team class but im getting a compiling error. if anyone can give me some insight it will be well appreciated.
public class Driver{
public static void main(String args[]) throws Exception{
//All information is stored in input.txt and is being
//read in below.
Scanner input = new Scanner(new File("input.txt"));
//Creates a new League and passes in a String signifying
//which league it is.
League american = new League("AL");
League national = new League("NL");
for(int i=0; i<15; i++){
//Creates a new team and adds the current team
//to the american league.
//You can assume there are exactly 15 teams in each league.
Team temp = new Team(input.next());
american.add(temp); // compile error
}
for(int i=0; i<15; i++){
//Creates a new team and adds the current team
//to the national league.
//You can assume there are exactly 15 teams in each league.
Team temp = new Team(input.next());
national.add(temp); // compile error
}
}
my League class
public class League{
private String league;
public League(String League){
league = League;
}
public void setLeagueAmerican(String League){
this.league = League;
}
public String getLeagueAmerican(){
return league;
}
public void setLeagueNational(String national){
this.league = national;
}
public String getLeagueNational(){
return league;
}
public void League( String League){
league = League;
}
}
my Team Class
public class Team
{
// instance variables - replace the example below with your own
private String team;
/**
* Constructor for objects of class Team
*/
public Team(String Team)
{
team = Team;
}
public void setTeam(String Team){
this.team = Team;
}
public String getTeam(){
return team;
}
public String add(League y)
{
return y; //compiling error
}
}

public String add(League y)
{
return y; //compiling error
}
This function returns a String. You are passing the parameter y, which is a League. You then try to return the very same League as if it was a String, which produces the error.
Either change the return type to be a League, or don't return y but a meaningful String (or even y.toString())

Related

Looking through class Arraylist objects without nested loops

I had this object oriented programming project last semester and it was all about simulating a simple dormitory.
1.There should have been a manager class in which the main method and like 80 percent of the other methods had to be there.
2.A dormitory class containing an arraylist of blocks.
3.A block class containing an arraylist of rooms.
4.A room class containing an arraylist of students.
5.All of these classes contained getters and setters for their private variables.
There were a few methods that we should've added to the program which has nothing to do with my question,so I will not write them in here,but the thing is,a few of theses methods needed to look through these arraylists to find a specific object.For example,a student with a specific student number.I created these methods with nested loops.But I know there is some way I could avoid heavy nesting.
Here is my reduced code.I will only let the manager class contain one nested loop method as an example:
import java.util.Scanner;
public class Manager {
private String name;
private String familyName;
private String userName;
private String passWord;
private static Scanner scan = new Scanner(System.in);
private Dormitory dorm = new Dormitory();
private static Menu menu = new Menu();
private Student tempStudent;
private Block tempBlock;
private Room room;
private boolean bool;
{
dorm.setDormManager(this);
}
public Manager(String managerName, String managerID) {
name = managerName;
userName = managerID;
}
//find student with its number
public void findStudent() {
//Taking the student number from the user.
System.out.println("Please enter the student number:");
String studentNum = scan.nextLine();
for (int i = 0; i < dorm.getBlockList().size(); i++)
for (int j = 0; j < dorm.getBlockList().get(i).getRooms().size(); j++)
for (int k = 0; k < dorm.getBlockList().get(i).getRooms().get(j).getRoomStudents().size(); k++)
if (dorm.getBlockList().get(i).getRooms().get(j).getRoomStudents().get(k).getStudentNumber().equals(studentNum)) {
tempStudent = dorm.getBlockList().get(i).getRooms().get(j).getRoomStudents().get(k);
break;
}
}
public void create() {
//Used loops for the original program.
Block block1 = new Block("1");
Block block2 = new Block("2");
dorm.getBlockList().add(block1);
dorm.getBlockList().add(block2);
Room room1 = new Room("1");
Room room2 = new Room("2");
dorm.getBlockList().get(0).getRooms().add(room1);
dorm.getBlockList().get(1).getRooms().add(room2);
Student student1 = new Student("12345678");
Student student2 = new Student("98765432");
dorm.getBlockList().get(0).getRooms().get(0).getRoomStudents().add(student1);
dorm.getBlockList().get(1).getRooms().get(0).getRoomStudents().add(student2);
}
public static void main(String[] args) {
Manager manager = new Manager("Dumbledore", "#1112");
manager.create();
}
}
public class Dormitory {
private int blocks;
private Manager dormManager;
private long allMembers;
private ArrayList<Block> blockList = new ArrayList<Block>();
}
public class Block {
private String blockNumber;
private ArrayList<Room> rooms = new ArrayList<Room>();
private Dormitory dorm = new Dormitory();
public Block(String blockNum) {
blockNumber = blockNum;
}
}
public class Room {
private String roomNumber;
private ArrayList<Student> roomStudents = new ArrayList<Student>();
private Block roomBlock;
private Student roomManager;
public Room(String roomNum) {
roomNumber = roomNum;
}
}
public class Student {
private String studentName;
private String studentFamilyName;
private String studentNumber;
private Room room;
public Student(String studentNum) { //Creates a student object using the student number.
studentNumber = studentNum;
}
}
I tried my best to reduce the code.
I searched a lot and asked a lot of people about this but I didn't get my desired answer.I'm not sure why I couldn't find anything about this,but I'd really appreciate it if you'd lend me a hand or give me the link of a related article.
Short answer: No, you should never loop through everything checking for getStudentNumber().equals(studentNum). This has linear time complexity O(N)
Long answer: You should index your data based on your queries
Eg: Indexing with HashMaps which have constant time complexity O(1). (Note: This code is not thread safe)
public class SchoolService {
private Map<String, Student> studentsById = new HashMap<>();
private Map<Long, Dorm> dormsById = new HashMap<>();
/// dormsByAreaCode is showing an example of an index which groups objects into lists
private Map<String, List<Dorm>> dormsByAreaCode = new HashMap<>();
public void addStudent(Student student) {
if (studentsById.containsKey(student.getName()) {
throw new IllegalStateException("Duplicate student " + student.getName());
}
studentsById.put(student.getId(), student);
}
public Student getStudentById(String studentId) {
Student student = studentsById.get(studentId);
if (student == null) {
throw new IllegalStateException("No such student " + studentId);
}
return student;
}
public void addDorm(Dorm dorm) {
// TODO: validation
dormsById.put(dorm.getId(), dorm);
List<Dorm> areaDorms = dormsByAreaCode.get(dorm.getAreaCode());
if (areaDorms == null) {
areaDorms = new ArrayList<>();
dormsByAreaCode.put(dorm.getAreaCode(), areaDorms);
}
areaDorms.add(dorm);
}
public Dorm getDormById(long dormId) {
Dorm dorm = dormsById.get(id);
// TODO: validation
return dorm;
}
public List<Dorm> getDormsByAreaCode(String areaCode) {
List<Dorm> areaDorms = dormsByAreaCode.get(areaCode);
// TODO: validation
return areaDorms;
}
// etc
}
The following quote is from tutorialspoint. This is the perfect use case of the forEach method from the Stream interface. The link I provided and further reading on Streams can help avoid repetitive code.
Using collections framework in Java, a developer has to use loops and make repeated checks. Another concern is efficiency; as multi-core processors are available at ease, a Java developer has to write parallel code processing that can be pretty error-prone.
dorm.getBlockList().stream().forEach((b) -> {
b.getRooms().stream().forEach((r) -> {
...
})
});
You can also read about parallelStreams from here.

Infinite loop when trying to populate a list of no more than two Hospitals

In this project the user must enter 1 or 2 hospitals but not 3 or more. So the program starts and I display a menu. If the user presses 1 he must enter a hospital(name and department). After this the program displays the menu again and the user can choose to insert another hospital.
But after that, if I choose to insert another one (which is not permitted) the program accepts it. It seems that every time InsertHospitals() is called from the main class, the value of numberofhospitals (which is a counter counting how many hospitals I entered) equals 0.
public class Hospital {
private String Name, Departments;
private char flag;
private int numberofhospitals;
private Hospital[] ListOfHospitals;
//private Patient[] ListOfPatiens;
//private Doctor[] ListOfDoctors;
//private Examination[] ListOfExaminations;
//private Folder[] ListOfFolders;
public Hospital(String Name, String Departments)
{
this.Name=Name;
this.Departments=Departments;
}
public Hospital()
{
ListOfHospitals = new Hospital[2];
//ListOfPatiens = new Patient[100];
//ListOfDoctors = new Doctor[100];
//ListOfExaminations = new Examination[100];
//ListOfFolders = new Folder[100];
}
public String getName()
{
return Name;
}
public void setname(String Name)
{
this.Name=Name;
}
public String getDepartments()
{
return Departments;
}
public void setdepartments(String Departments)
{
this.Departments=Departments;
}
public void InsertHospitals()
{
if(numberofhospitals==2)
{
System.out.println("You can give only two hospitals!");
}
else
{
String temp = sir.readString("Hospital's Name:");
Name=temp;
String temp1 = sir.readString("Hospital's departments:");
Departments=temp1;
Hospital hospital = new Hospital(Name, Departments);
ListOfHospitals[numberofhospitals]=hospital;
numberofhospitals=numberofhospitals+1;
}
}
}
Your misunderstanding something, the list of hospitals (as mentioned) should not be inside your hospital class. You have to consider your hospital class as a blueprint you are using in your application.
Which means that you need to have a list of hospitals, as a list inside your other application class (which runs the application) and the InsertHospitals method should not be in your hospital class either obviously.
As you add a new hospital in your program, you create a new hospital object and add it to the list of hospitals (fx an arraylist) your keeping as a field value.
Also posssibly make a new constructor with parameters in the hospital class so you can insert the values outside of the class.
Something like this fx.
public class MainApp {
private ArrayList<Hospital> hospitalList;
public static void main(String[] args) {
// Initialize or load it from a file or whatever here.
hospitalList = new ArrayList<Hospital>();
// your code here...
}
public void insertHospital(<insert parameters here to create a hospital>) {
Hospital newHospital = new Hospital(<insert params with new constructor>);
hospitalList.add(newHospital);
}
}
Whatever your problem, your program completely wrong. In insertHospital() your changing Name and Departments fields, and creating new Hospital with those values. When you print Hospital information all hospitals will have the same value.

Java - Using an object inside an object

I am working on a project ( I had a problem yesterday and so many people helped me!) so I decided to ask for help again.
My code has 3 classes. ProjectMain,Students,Classroom. I created an array of Classroom objects. Right now I have 3 Classroom objects. But I have to assign student objects to these Classroom objects. For example : classarray[0] is an object from Classroom class and studentobject.get(0) , studentobject.get(1) ... will be students objects inside classarray[0] object. But I have failed on this while coding. Here are my classes :
public class Classroom
{
private String classname;
private String word[] = null;
protected ArrayList<Students> studentobject = new ArrayList<Students>(10);
public String[] getWord()
{
return word;
}
public void setWord(String[] word)
{
this.word = word;
}
public ArrayList<Students> getStudentobject()
{
return studentobject;
}
public void setStudentobject(ArrayList<Students> studentobject)
{
this.studentobject = studentobject;
}
public String getClassname()
{
return classname;
}
public void setClassname(String classname)
{
this.classname = classname;
}
public void classroomreader(String filename)
{
// This method gets the name of Classroom
File text = new File("C:/Users/Lab/Desktop/classlists/" + filename
+ ".txt");
Scanner scan;
try
{
scan = new Scanner(text);
String line = scan.nextLine();
word = line.split("\t");
line = scan.nextLine();
word = line.split("\t");
} catch (FileNotFoundException e1)
{
e1.printStackTrace();
}
}
}
This is my student class :
public class Students extends Classroom
{
private String name,id;
private int age;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
And my main class :
public class ProjectMain
{
public static void main(String[] args)
{
Classroom[] classarray = new Classroom[3];
//I got 3 Classroom objects here
classarray[0]=new Classroom();
classarray[1]=new Classroom();
classarray[2]=new Classroom();
classarray[0].classroomreader("class1");
classarray[0].studentobject.get(0).setName(classarray[0].getWord()[1]);
//The problem is in here. When my code comes to the line above,
// at java.util.ArrayList.rangeCheck(Unknown Source) error comes out.
// I tried to get first object in studentobject Arraylist, and tried to set it's name
// to the variable which my text reader reads.
How can I write what I have in my mind?
Your classroomreader method reads the file but don't do much of it... maybe you want to create some instance of Students within it.
scan = new Scanner(text);
String line = scan.nextLine();
word = line.split("\t"); // won't be used
line = scan.nextLine();
word = line.split("\t"); // erased here
There you only have the last line (split) of the file in word attribute.
When creating Classroom instance studentobject list is created empty and it stays that way so you can't access first (or any) object in it.
To populate your list you may add to Classroom method like this:
public void addStudent(Student s)
{
studentobject.add(s);
}
classroom contains the following field declaration
String word[] = null;
the main class, incl the classroomreader does not set a value to this field. Yet you are going to invoke
classarray[0].getWord()[1]
which then must fail.
tip: don't use expressions like this, which can be found in your main class (at least not in early stages of development, or learning)
classarray[0].studentobject.get(0).setName(classarray[0].getWord()[1]);
resolve into variables and several steps. Compilers are smart enough to produce the same code if the context is not disturbed, ie the long expression is resolved into a single block.
Never forget that the purpose of programming languages is to make programs readable for humans. :) Code with abbreviations or "tricks" simply shows some philodoxical attitude (imho)

Arraylist Java Binding errors

I need to create my own registry for a school project.
I would like to have
1
room, room
2
room, room
hall, hall
3
room, room
hall, hall
dorm, dorm
But all I am getting is
1
room,room
2
room,hall
hall,hall
3
room,dorm
hall,dorm
dorm,dorm
So somehow the the facility reference got changed somewhere but i have no idea how to fix this. Can anyone help?
These are my codes.
public class registry {
static List<registryRecord> register = new ArrayList<registryRecord>();
public static boolean bind(String name, facility ref){
for(registryRecord r:register){
if(r.name.equals(name)) //check if the name is already binded
return false;
}
registryRecord newRecord = new registryRecord(name, ref);
register.add(newRecord);
for (registryRecord r:register){
System.out.println(r.name +","+ r.ref.name);
}
return true;
}
public class registryRecord {
String name;
facility ref;
public registryRecord(String name, facility ref){
this.name = name;
this.ref = ref;
}
public class server {
public static void main(String args[]) throws Exception{
facility room = new facility("room");
System.out.println(1);
boolean test = registry.bind("room", room);
facility hall = new facility("hall");
System.out.println(2);
boolean test2 = registry.bind("hall", hall);
facility dorm = new facility("dorm");
System.out.println(3);
registry.bind("dorm", dorm);
}
public class facility {
public static String name;
static List<booking> bookings;
public facility(String name){
this.name=name;
this.bookings = new ArrayList<booking>();
}
}
As I suspected, since name is static in facility, it is shared between all instances. This means that it gets overwritten each time you create a new instance.
Just remove static from both your fields, and your program should work fine.

Can I use my objects without fully populating them?

I have situation. I have to create a Sports Club system in JAVA. There should be a class your for keeping track of club name, president name and braches the club has. For each sports branch also there should be a class for keeping track of a list of players. Also each player should have a name, number, position and salary.
So, I come up with this. Three seperate classes:
public class Team
{
String clubName;
String preName;
Branch []branches;
}
public class Branch
{
Player[] players;
}
public class Player
{
String name;
String pos;
int salary;
int number;
}
The problems are creating Branch[] in another class and same for the Player[]. Is there any simplier thing to do this? For example, I want to add info for only the club name, president name and branches of the club, in this situation, won't i have to enter players,names,salaries etc. since they are nested in each other. I hope i could be clear. For further questions you can ask.
Here's a more complete, formal example of your scenario using conventional Accessors/Mutators (getters/setters), constructors, and Lists. The main() method below illustrates how to use your classes.
public class SportsClub
{
public static void main(String[] args)
{
//Create a team without any branches
Team myTeam = new Team("Southpaws", "South");
//Create a new Branch without any players
Branch myBranch = new Branch();
//Add myBranch to myTeam
myTeam.getBranches().add(myBranch);
//Create a new player
Player myPlayer = new Player("Bob", "Center", 120, 3);
//Add myPlayer to myBranch (and therefore myTeam)
myBranch.getPlayers().add(player);
}
}
public class Team
{
private String clubName;
private String preName;
private List<Branch> branches;
public Team(String clubName, String preName)
{
this.clubName = clubName;
this.preName = preName;
branches = new ArrayList<Branch>();
}
public String getClubName() { return clubName; }
public String getPreName() { return preName; }
public List<Branch> getBranches() { return branches; }
public void setClubName(String clubName) { this.clubName = clubName; }
public void setPreName(String preName) { this.preName = preName; }
public void setBranches(List<Branch> branches) { this.branches = branches; }
}
public class Branch
{
private List<Player> players = new ArrayList<Player>();
public Branch() {}
public List<Player> getPlayers() { return players; }
public void setPlayers(List<Player> players) { this.players = players; }
}
public class Player
{
private String name;
private String pos;
private Integer salary;
private Integer number;
public Player(String name, String pos, Integer salary, Integer number)
{
this.name = name;
this.pos = pos;
this.salary = salary;
this.number = number;
}
public String getName() { return name; }
public String getPos() { return pos; }
public Integer getSalary() { return salary; }
public Integer getNumber() { return number; }
public void setName(String name) { this.name = name; }
public void setPos(String pos) { this.pos = pos; }
public void setSalary(Integer salary) { this.salary = salary; }
public void setNumber(Integer number) { this.number = number; }
}
To answer your question, yes, you can create these objects without populating the Lists with players. The SportsClub.main() above illustrates that.
I would use a List rather than an array since they're (easily) dynamically resizable, but otherwise, you're on the right track.
Think about encapsulation and visibility too. Make all those fields private and provide accessors.
You could create an empty Branch[] array (or better yet - a list) at initialization and add to it later, that way you don't have to enter all the information upon creation - same goes for Player[].
Something like:
public class Team
{
String clubName;
String preName;
private List<Branch> branches;
public Team (String club, String pre) {
clubName = club;
preName = pre;
branches = new LinkedList<Branch>();
}
public void addBranch (Branch branch) {..}
}
public class Branch
{
private List<Player> players;
public Branch () {
players = new LinkedList<Player>();
}
public void addPlayer (Player player) {..}
}
public class Player
{
String name;
String pos;
int salary;
int number;
}
I think that's good. You should probably have methods in the classes to manage your information though--don't try to do anything serious from "Outside" these classes.
to be more specific: All your members should be private and only used/accessed from within the classes--also in general avoid setters and getters, instead ask the class to do things for you.
For example, if you wanted to know how many players were in a branch, you would call branch.countPlayers, not access the Player array to count the players from outside.
If you wanted to know how many players were in a team, you would call team.countPlayers which would call branch.countPlayers for each Branch, sum them up and return the value.
If you wanted to see which branch a player was in, you would call Team.findPlayer(playerName). Team would call branch.hasPlayer(playerName) on each branch until it returned a true, then Team would return the Branch object that returned true.
etc.
Note that this resolves your "Populated or not" issue. If you simply have methods like "hasBranch()", "addBranch()", "removeBranch()" then it doesn't matter how or when you populate the branches array since you control it all within the Team class you can change it's implementation at any time and not change a single line outside that class.
You won't have to enter anything into the players array, nor the branch[]. Provided you make the fields accessible, of have properties, you will be able to put them in however you like.
The class structure looks good to me, but a List would be better so that you don't have to worry about resizing arrays down the road.
Nothing wrong with your classes. I personally would use a strongly-typed List to store the branches and players:
public class Team
{
String clubName;
String preName;
List<Branch> branches;
}
public class Branch
{
List<Player> players;
}
Not sure of the requirement, but you'd probably want to have some kind of identifier or name for each Branch, right?
There's nothing in these classes that forces you to create new players just to instantiate a Branch. The list of Players can remain null or empty until you need them.

Categories

Resources