Before I post my question, I just need guidance on how to improve my java program, because I want to learn.
So, for my assignment I need to:
Create 3 classes, app, football player and football team.The application (app) will use the two other classes (football player and football team).
app will
create 11 football players (you can place them in an array or
ArrayList)
create a football team using the players above use the
football team instance (object) to display the information requested
in the lab
a football player class
has at least 5 attributes from
your choice a method that returns the complete info about the player
a football team class has
a name and a mascot
11 football players
any other attributes (optional)
a method that displays all the information about a team including:
name
mascot, and information on each player in the team
a method that display information about a specific player in the team using an input parameter such as the player position or player number for instance. For instance, from team A, displays information about the quarterback, or display information about player number 5.
I'm confused with my team class. I don't know how to add 11 players to the class and provide an input parameter for the player instance. I'm unsure about my app class because I don't know how to use the football team instance (object) to display the information requested in the lab.
Here is what I have so far
public class app {
public static void main(String[] args)
{
player pl1 = new player
("Christian","Campbell","Cornerback","Alabama","Central");
System.out.println(pl1.getInfo());
player pl2 = new player
("Marcus","Allen","Safety","Maryland","Dr. Henry A. Wise, Jr");
System.out.println(pl2.getInfo());
player pl3 = new player
("Tommy","Stevens","Quarterback","Indiana","Decatur Central");
System.out.println(pl3.getInfo());
player pl4 = new player
("Nyeem","Wartman-White", "Linebacker","Pennsylvania","Valley View");
System.out.println(pl4.getInfo());
player pl5 = new player
("George", "Foreman", "Defensive back","Georgia","Parkview");
System.out.println(pl5.getInfo());
player pl6 = new player
("Andre","Robinson","Right Tackle","Pennsylvania","Bishop McDevitt");
System.out.println(pl6.getInfo());
player pl7 = new player
("Malik","Golden","Safety","Connecticut","Chesire Academy");
System.out.println(pl7.getInfo());
player pl8 = new player
("Koa","Farmer","Safety","California","Notre Dame");
System.out.println(pl8.getInfo());
player pl9 = new player
("Jake","Zembiec","Quarterback","New York","Aquinas Institute");
System.out.println(pl9.getInfo());
player pl10 = new player
("Brandon","Polk","Wide Receiver","Virgina","Briar Woods");
System.out.println(pl10.getInfo());
player pl11 = new player
("Trace","McSorley","Quarterback","Virgina","Briar Woods");
System.out.println(pl11.getInfo());
}
}
public class player {
//---------Declaring attributes----
String firstName;
String lastName;
String position;
String State;
String Highschool;
player (String inf_firstName, String inf_lastName, String inf_position, String inf_State, String inf_Highschool)
{
firstName = inf_firstName;
lastName = inf_lastName;
position = inf_position;
State = inf_State;
Highschool = inf_Highschool;
}
String getInfo()
{
return "Name: "+firstName+ " "+lastName+", "+"position: " +position+ ", State: " +State+ ", High School: " +Highschool;
}
}
public class team {
String team = "Penn State";
String mascot = "Nittany Lions";
team(String inf_team, String inf_mascot)
{
team = inf_team;
mascot = inf_mascot;
}
team t1 = new team("Penn State", "Nittany Lions");
String getInfo()
{
return "Team Name: "+team+ "Team Mascot: "+mascot;
}
}
In your team class, below String team and String mascot, you need a player[] players array. And in your constructor, pass in an array that contains all your players.
2 options -
in your main method you create an array and add all of your players to it, and then pass it to your Team constructor, which sets an internal array to the value of the passed in array
or your Team object has a method called something like addPlayer(player) which adds the player to your Team's internal player array. Then you invoke the method after each player creation.
also you should uppercase your class names.. like Team, Player, etc.
I didn't write the getter or setter methods for the instance variables, because I think you can figure those out. But from your description of the Team class, it could look something like this.
public class Team {
//Instance variables and constants
private static final int MAX_PLAYERS = 11;
private Player[] players;
private String name;
private String mascot;
//Constructor
public Team(String name, String mascot) {
this.name = name;
this.mascot = mascot;
this.players = new Player[MAX_PLAYERS];
}
//Add players to the team
public void addPlayers(List<Player> p) {
//Ensures only 11 players are added to the team
for (int i = 0; i < MAX_PLAYERS; i++)
this.players[i] = p.get(i);
}
}
To match the implementation of this Team class, your App should be more of something like this, to be able to pass an already build List<Player> to the addPlayers method of the Team class...
public class app {
public static void main(String[] args) {
List<Player> players = new ArrayList<>();
players.add(new Player(/* Parameters for each player object */));
//Not writing this 11 times!
Team team = new Team("The Bulldogs", "Bull Dog");
team.addPlayers(players);
}
}
Since you have 11 players,It would better of creating an array of objects as they share similar properties. Like this:
Player[] players = new Player[11];
And then add their parameters and then pass it to the constructor class of app, which takes a list of a palyers.
I have updated your solution. This is how you can create your classes and method.
Please see inline comments for more information. Hope this helps.
public class App {
public static void main(String[] args) {
//creating a team
Team t1 = new Team("Penn State", "Nittany Lions");
Player pl1 = new Player("Christian", "Campbell", "Cornerback", "Alabama", "Central");
System.out.println(pl1.getInfo());
//for example, adding one player to the team t1 created above.
t1.addPlayer(pl1);
//you can repeat this step for adding all the teams
Player pl2 = new Player("Marcus", "Allen", "Safety", "Maryland", "Dr. Henry A. Wise, Jr");
System.out.println(pl2.getInfo());
Player pl3 = new Player("Tommy", "Stevens", "Quarterback", "Indiana", "Decatur Central");
System.out.println(pl3.getInfo());
Player pl4 = new Player("Nyeem", "Wartman-White", "Linebacker", "Pennsylvania", "Valley View");
System.out.println(pl4.getInfo());
Player pl5 = new Player("George", "Foreman", "Defensive back", "Georgia", "Parkview");
System.out.println(pl5.getInfo());
Player pl6 = new Player("Andre", "Robinson", "Right Tackle", "Pennsylvania", "Bishop McDevitt");
System.out.println(pl6.getInfo());
Player pl7 = new Player("Malik", "Golden", "Safety", "Connecticut", "Chesire Academy");
System.out.println(pl7.getInfo());
Player pl8 = new Player("Koa", "Farmer", "Safety", "California", "Notre Dame");
System.out.println(pl8.getInfo());
Player pl9 = new Player("Jake", "Zembiec", "Quarterback", "New York", "Aquinas Institute");
System.out.println(pl9.getInfo());
Player pl10 = new Player("Brandon", "Polk", "Wide Receiver", "Virgina", "Briar Woods");
System.out.println(pl10.getInfo());
Player pl11 = new Player("Trace", "McSorley", "Quarterback", "Virgina", "Briar Woods");
System.out.println(pl11.getInfo());
}
}
class Player {
// ---------Declaring attributes----
String firstName;
String lastName;
String position;
String State;
String Highschool;
Player(String inf_firstName, String inf_lastName, String inf_position, String inf_State, String inf_Highschool) {
firstName = inf_firstName;
lastName = inf_lastName;
position = inf_position;
State = inf_State;
Highschool = inf_Highschool;
}
String getInfo() {
return "Name: " + firstName + " " + lastName + ", " + "position: " + position + ", State: " + State
+ ", High School: " + Highschool;
}
}
class Team {
String team = "Penn State";
String mascot = "Nittany Lions";
Player[] playerArr = new Player[11]; //this is the main part. Array of players (11)
int playerCount = 0; //this will track the number of players being added to the team.
Team(String inf_team, String inf_mascot) {
team = inf_team;
mascot = inf_mascot;
}
public String getInfo() {
return "Team Name: " + team + "Team Mascot: " + mascot;
}
//Using this method you can add the players to the Player Array.
public void addPlayer(Player player) {
if (playerCount < 11) {
playerArr[playerCount] = player;
playerCount++;
}
}
//Using this method you find out a player with specific quality
//like in this case its position of the player.
//you can iterate through the Players Array and can find out the player
// And after that you can get the information of the player by your method
//getInfo
public String getPlayerInfo(String positionTemp) {
Player player = null;
for (int i = 0; i < playerArr.length; i++) {
if (playerArr[i].position.equals(positionTemp)) {
player = playerArr[i];
break;
}
}
return player.getInfo();
}
}
Related
Class Hospital
package app;
import java.util.ArrayList;
import app.Department;
public class Hospital {
String hospitalId;
String hospitalName;
int departmentCount;
ArrayList<Department> departmentList = new ArrayList<Department>();
public Hospital(String hospitalId, String hospitalName, ArrayList<Department> departmentList, int departmentCount) {
this.hospitalId = hospitalId;
this.hospitalName = hospitalName;
this.departmentList = departmentList;
this.departmentCount = departmentCount;
}
public ArrayList<Department> getDepartmentList() {
System.out.println("Returning " + departmentList.size());
return departmentList;
}
}
Class Department
package app;
public class Department {
String departmentId;
private String hospitalDeptName;
String hospitalDeptType;
String subtypeBitFlag;
String status;
public Department(String departmentId, String hospitalDeptName, String hospitalDeptType, String subtypeBitFlag, String status) {
this.departmentId = departmentId;
this.hospitalDeptName = hospitalDeptName;
this.hospitalDeptType = hospitalDeptType;
this.subtypeBitFlag = subtypeBitFlag;
this.status = status;
}
public String getDepartmentName() {
return hospitalDeptName;
}
}
I am creating an object Department and storing them in an ArrayList
ArrayList<Department> departmentList = new ArrayList<Department>();
departmentList.add(new Department(departmentId, hospitalDeptName, hospitalDeptType, subtypeBitFlag, status));
I am creating an object Hospital and passing to the constructor the above departmentList as list of Departments
ArrayList<Hospital> hospitalList = new ArrayList<Hospital>();
Hospital hospital = new Hospital(hospitalId, hospitalName, departmentList, departmentList.size());
Looping over the hospital objects and extracting the information
for (Hospital hospital : hospitalList) {
System.out.println("The number of departments is: "+hospital.departmentList.size() + " for Hospital: " + hospital.hospitalId );
for (Department department : hospital.departmentList) {
System.out.println("Hospital ID: " +hospital.hospitalId + ", Hospital Name: "+ hospital.hospitalName + ", Department Name: " + department.getDepartmentName());
}
}
Logs as seen below. I am not able to retrive the department and not even their values. But... I am able to retrieve anything other that ArrayList from the object Hospital.
The count 0 proves is as if the object Hospital is not populating the array list of Department
The number of departments is: 0 for Hospital: q
The number of departments is: 0 for Hospital: a
The number of departments is: 0 for Hospital: s
The number of departments is: 0 for Hospital: 1
The number of departments is: 0 for Hospital: 2
The number of departments is: 0 for Hospital: 3
You made just one arraylist, and all the hospitals just have a reference to the same list, which you later clear, hence, that got rid of all departments.
Let's take it one step at a time:
ArrayList<Department> departmentList = new ArrayList<Department>();
This makes a new arraylist object, assigns the reference to it to a newly declared local variable named departmentList. new ArrayList() is like "build a house" and ArrayList<Department> departmentList; is like 'open up a new page in your address book and title it "departmentList". departmentList = new... is: Write the address to that house down in the address book. Crucial take awawy: departmentList is not the same as the list - it's a reference to it - it's the page in the address book that you can use to get to the house, not the house itself.
departmentList.add(new Department(departmentId, hospitalDeptName, > hospitalDeptType, subtypeBitFlag, status));
. is the dereference operator: This is the equivalent of "Take the page in your address book titled "departmentList" and then go walk over to the house itself. Open the door and yell "ADD!" at it. Things will probably happen when you do this.
Hospital hospital = new Hospital(hospitalId, hospitalName, departmentList, departmentList.size());
Focusing on the departmentList part: This says: "Grab a piece of paper and copy the address over onto it, then hand that piece of paper to the hospital constructor". It does not clone the list.
public Hospital(String hospitalId, String hospitalName, ArrayList<Department> departmentList, int departmentCount) {
this.departmentList = departmentList;
}
More copying of address book pages. At no point did anybody copy a house anywhere.
Now there are many notebook pages floating about, all with the same address on it. If anybody that has a page decides to visit a house and toss a brick through the window, everybody else will see that too. This isn't good - someone can change the departmentlist in your hospital now. You probably wanted to clone that arraylist instead.
Your Hospital constructor should probably have:
this.departmentList = List.copyOf(departmentList);
instead.
For my school examn I have to make a console-application game of Hangman in Java, in which a player should be able to play against another player or a computer (2 players). A player should however also be able to play against a computer/AI. On top of that computers should be able to play against a computer as well.
Given the above, I have defined HashMaps with the player's names as String indexes and respective objects as values, like so:
private HashMap<String, PlayerHuman> humans = new HashMap<>(2);
private HashMap<String, PlayerComputer> computers = new HashMap<>(2);
Since both 2 players and 2 computers can play against each other, both HashMaps have a capacity of 2. Now when creating the players, there should either be real names entered (e.g. "John", "Mary") or a simple "C" if a player is computer-controlled. I then run a check on wether the input given was a "C" or not, resulting in creating the respective class for that player, like so:
Scanner scanner = new Scanner(System.in);
System.out.println("First create the players for the game!");
//
System.out.println("Type the name of player 1 (type C for computer): ");
String playerName1 = scanner.nextLine();
System.out.println("Type the nam of player 2 (type C for computer): ");
String playerName2 = scanner.nextLine();
if (playerName1.equals("C")) {
PlayerComputer player1 = new PlayerComputer();
player1.setPlayerName(playerName1);
if (playerName2.equals("C")) {
playerName1 = "C1";
playerName2 = "C2";
PlayerComputer player2 = new PlayerComputer();
player1.setPlayerName(playerName1);
player2.setPlayerName(playerName2);
this.computers.put(playerName2, player2);
} else {
PlayerHuman player2 = new PlayerHuman();
player2.setPlayerName(playerName2);
this.humans.put(playerName2, player2);
}
this.computers.put(playerName1, player1);
} else {
PlayerHuman player1 = new PlayerHuman();
player1.setPlayerName(playerName1);
if (playerName2.equals("C")) {
PlayerComputer player2 = new PlayerComputer();
player2.setPlayerName(playerName2);
this.computers.put(playerName2, player2);
} else {
PlayerHuman player2 = new PlayerHuman();
player2.setPlayerName(playerName2);
this.humans.put(playerName2, player2);
}
this.humans.put(playerName1, player1);
}
String startingPlayer = raffle(playerName1, playerName2);
There is definitely an easier way to do this, I have just run completely stuck and do not see a way out anymore. I then have to randomly select either of 2 players to be the first to play. I do this in the following method "raffle".
private String raffle(String nameOne, String nameTwo) {
Random random = new Random();
String raffledName = random.nextBoolean() ? nameOne : nameTwo;
System.out.println(raffledName + " may begin!");
return raffledName;
}
After this is where I run stuck. I'm getting the expected result from the "raffle" method; one of two given player's names, however I'm lost on how to make the code know which array to retrieve the returned player from, as a computer could either be named "C", or "C1" and "C2" when both players are computer-controlled, to know which computer represents which player. How do I make my code take this into consideration when retrieving the player's respective instance?
Any suggestions on creating the players are welcome too, since I feel the above written code is dirty and too procedural.
Thanks in advance!
I would like to suggest that you define a super class "Player" that your two player types derive from.
abstract class Player {
private String name;
public void setPlayerName(String name) {
this.name = name;
}
public String getPlayerName() { return name; }
abstract public boolean isCPU();
...
}
class PlayerHuman extends Player {
public boolean isCPU() { return false; }
...
}
class PlayerComputer extends Player {
public boolean isCPU() { return true; }
...
}
HashMap<String, Player> players = ...
Or, you can just use an array for players:
Player[] players = new Player[2];
You don't have to refer to player by name, then, and you can shuffle the array to decide who goes first.
FULL GITHUB FILES FOUND HERE
This is class Roulette.java
public static void main(String[] args) {
System.out.println("Welcome to roulette " + Casino.player());
}
This is class Casino.java
public static String player() {
Scanner sc = new Scanner(System.in);
String name;
System.out.println("Please enter your name : ");
name = sc.nextLine();
return name;
}
When running Roulette.java it's not printing Casino.player() as a variable of your name, but running the function and asking for your name. I want to run Casino.java first,ask your name, then run roulette and welcome you with your name. NOT ASK YOUR NAME AGAIN.
Note: New to programming
The player() method in the Casino class prints out the message to input the users name. This will happen every time the method is called. To do what you want to do you need to create a conditional that checks if the player has already been set.
NOTE: This is not good practice or class design and in the future you should look into proper practice for class design and setting fields in a class. I would suggest posting this code on Code Review once you get it working to get a full answer on how this design can be improved.
Your Casino class should look something like this:
public class Casino {
private static String player = "";
public static String player() {
if (player.equals("")) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter your name : ");
this.player = sc.nextLine();;
}
return player;
}
}
Try something like this
String player = Casino.player();
System.out.println("Welcome to roulette " + player);
I have this method addPerson (on the main) which is used to set the name of a person.
private static Person[] addPerson(Person _person[], int _minAge, int _id){
int personAge;
String personName;
Scanner scan = new Scanner(System.in);
System.out.println("What's his age?");
personAge = scan.nextInt();
if(personAge >= _minAge){
if(!_person[_id].getPerson().equals("")){
System.out.println("Person " + _person[_id].getPerson() + " already exists.");
}else{
System.out.println("Enter the name of the person");
Scanner addPerson = new Scanner(System.in);
personName = addPerson.next();
_person[_id].setPerson(personName);
}
}else{
System.out.println("Person is not old enough");
}
return _person;
}
And here is the method setPerson in my custom class which is used to set the name of the person.
public void setPerson(String name){
System.out.println("Person added");
personName = name;
}
I know I should be doing the checking on whether that person already exists inside my setPerson method, but I am sort of confused with this. As you see I am expecting the user to input an integer, so I guess that I should check that right away to not get an error in case he inputs a string.
So my question is which should be checked within the same method and which on the method on my custom class?
Your code (and your question) is a bit confusing, but from what I can understand you want to know if you should check whether a person exists in the array in setPerson() or not?
Well, from what I can gather from your code, you should not do it in setPerson(), because that's a method in the Person class. The Person class shouldn't need to know anything about your array of Person objects.
So the way you're doing it now is probably your best bet.
Some general hints about the code:
There's no need to create a new Scanner, you can just use the one you have. So this
Scanner addPerson = new Scanner(System.in);
personName = addPerson.next();
becomes this
personName = scan.next();
I would also suggest you use the name setName()instead of setPerson()for your method name, it doesn't make sense to have it named one way when what it's actually doing is something else.
I would do it this way. However I don't have java currently so I didn't test this snippet.
class Person {
private String name;
public void setName(String name) {
this.name = name;
}
}
class Main {
private static final int minAge = 22;
private static Map<Person> addPerson(Map<Person> people, int id) {
if(people.containsKey(id)) {
// print that person with this id exists
return people;
}
Scanner scanner = new Scanner(System.in);
int age = scanner.nextInt();
if(age < minAge) {
// print that given age is invalid
return people;
}
String name = scanner.next();
people.get(id).setName(name);
return people;
}
}
I'm completely new to Java, so I'm sorry if my question is dumb. Im working on this assignment, and I've been reading about main methods for hours now, but I just cant figure it out. I put some of my code below. I might be way off here, but what I'm hoping to accomplish is to get the main method to start the constructor, but when I compile I get an error saying "cannot find symbol - constructor Player". Now, Im guessing this has something to do with the string parameters of the constructor, but I'm all out. If anyone could shed some light on this, probably very simple problem, I'd be very happy :)
public class Player {
private String nick;
private String type;
private int health;
public static void main(String[] args)
{
Player player = new Player();
player.print();
}
public Player(String nickName, String playerType)
{
nick = nickName;
type = playerType;
health = 100;
System.out.println("Welcome " + nick +" the " + type + ". I hope you are ready for an adventure!");
}
public void print()
{
System.out.println("Name: " + nick);
System.out.println("Class: " + type);
System.out.println("Remanining Health: " + health);
}
Player has no no-arg constructor, you could use:
Player player = new Player("My Nickname", "Player Type");
If you wish to prompt the user for the Player arguments, you can read like so:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Player Name:");
String nickName = scanner.nextLine();
System.out.print("Enter Player Type:");
String playerType = scanner.nextLine();
Player player = new Player(nickName, playerType);
Clearly you are using 0-arg constructor, when you haven't got one: -
Player player = new Player();
Note that, when you provide a parameterized constructor in your class, the compiler will not add default constructor. You would have to add one 0-arg constructor manually, if you are using it.
So, either you can add one 0-arg constructor as such: -
public Player() {
this.nick = "";
this.type = "";
this.health = -1;
}
or, use the parameterized constructor to create the object.
When your class explicitly defines constructor, implicit no-arg constructor won't be created.
You have explicit constructor in your class
public Player(String nickName, String playerType)
{
nick = nickName;
type = playerType;
health = 100;
System.out.println("Welcome " + nick +" the " + type + ". I hope you are ready for an adventure!");
}
And trying to invoke no-arg constructor
Player player = new Player();
Either you need to pass parameters in above code (or) create no-arg constructor.
What you tried to do in your main()-method was to create a new Player object. But the problem is that you had to use the constructor you implemented (Player(String, String)) but you used a constructor without any parameters (Player()).
You should either use empty strings (e.g. if you want to get a player dummy)
Player player = new Player("","");
or you should give the new player instance the name and type you want to, so for example
Player player = new Player("flashdrive2049","Player");
Regards.
A default constructor is created by java when a construtor is missing, this construtor simply calls the super class. When you defined an explicit constructor java wont create one. So you can either define one default constructor in your class
e.g.
public Player()
{ nick = "abc";
type = "type";
health = 100;
System.out.println("Welcome " + nick +" the " + type + ". I hope you are ready for an adventure!");
}
or modify the code to call the constructor u defined.
Player player = new Player("nick","type");