I am relatively new to Java and as a newbie I have trouble understanding how the code works or executes. Most often I've figured out the answer in a minute or two, sometimes in an hour or two. However, I've been stuck for two days now and I'm afraid I can't work out the problem on my own.
The programming exercise that I'm currently working on is nearly finished, save for one bit that isn't working right: method setMaxSize doesn't seem to work the way it should. I've tried to edit the method addPlayer to make a IF-statement concerning the team's max size and current size. However, the method does not add players to the list, regardless of the fact that the team list is empty at the moment. What did I do wrong? Where's my mistake? How can I get the IF-statement in addPlayer to accept new players in an empty list while checking for the maximum possible number of players in team?
I'd appreciate any feedback I can get and I apologize if it's a noobish question, but I'm really running out of patience here. Also, it's not homework: it's a programming exercise I found online from a university website I found, but I have trouble finishing it.
I'm including the two class files and the main field.
import java.util.ArrayList;
public class Team {
private String name;
private ArrayList<Player> list = new ArrayList<Player>();
private int maxSize;
public Team (String name){
this.name = name;
}
public String getName(){
return this.name;
}
public void addPlayer(Player player){
if (list.size() <= this.maxSize){
this.list.add(new Player(player.getName(), player.goals()));
}
}
public void printPlayers(){
for (Player player : list){
System.out.println(player.toString());
}
}
public void setMaxSize(int maxSize){
this.maxSize = maxSize;
}
public int size(){
return this.list.size();
}
public int goals(){
int goalSum = 0;
for (Player player : list){
goalSum+=player.goals();
}
return goalSum;
}
}
public class Main {
public static void main(String[] args) {
Team barcelona = new Team("FC Barcelona");
Player brian = new Player("Brian");
Player pekka = new Player("Pekka", 39);
barcelona.addPlayer(brian);
barcelona.addPlayer(pekka);
barcelona.addPlayer(new Player("Mikael", 1));
System.out.println("Total goals: " + barcelona.goals());
}
}
public class Player {
private String name;
private int goal;
public Player(String name){
this.name = name;
}
public Player(String name, int goal){
this.name = name;
this.goal = goal;
}
public String getName(){
return this.name;
}
public int goals(){
return this.goal;
}
public String toString(){
return "Player: " + this.name + ", goals " + this.goal;
}
}
You need to call setMaxSize before adding players to the team.
As you have said before, you are never calling setMaxSize, so there is maxSize is initially 0. Additionally, I suggest making setters and getters for all your data fields in each class, and making each field private.
For example, you have a setter for maxSize, but not getter. It doesn't make much sense to do one but not the other, right? You create better encapsulation and allow for future changes of your code much easier this way, and again it is better practice for future projects.
Related
I'm trying to create a Sub-class for a program that creates a list with different objects.
One of my sub-classes is named "Jewelry". Here I need to specify if the material is "gold" or "silver". The different material has a different value. (Gold = 2000, Silver= 700) Im not allowed to use Boolean. Im a big beginner so sorry for the "easy" question. You guys have any tips? much appreciated. Code:
public class Jewellery extends Valuable {
private int numberOfJewels;
private String material;
private double value;
public Jewellery(String name, int numberOfJewels, String material) {
super(name);
this.material = material.valueOf(material);
this.numberOfJewels = numberOfJewels;
}
public int getNumberOfJewels(){
return numberOfJewels;
}
public String getMaterial() {
return material;
}
public double getValue(){
return value;
}
public double getValuePlusVAT() {
return value();
}
public String toString(){
return getName() + " " + this.getMaterial() + " " + getValuePlusVAT();
}
}
The fast answer can be... use a strings SWITCH then.
The elaborated one is keep a enum with pairs material/value so is more flexible, maintainable and reusable around the application
I am creating a dump Java app for student information system for learning and implementing OOPS Concepts like inheritance, abstraction, polymorphism and encapsulation.
What I am doing is, I have created Faculty Class, Student Class and a College Class. Now i want to add new faculty in College. So my approach is to create a method in College class i.e. addFaculty(Faculty f) and fireFaculty(Faculty f), now i want to add Faculties in College class.
Whats the best way to do it? How do i store list of Faculty Object in College Object. Because i can add more than one faculty and more than one student in college.
Whats the best approach to solve this problem in OOPS?
Here is College.java code which i have implemented, it works fine but is this the best way i can solve it?
public class College
{
String name;
String location;
String courses[];
HashMap<String,Faculty> faculties;
int noOfFaculties = 0;
int noOfStudents = 0;
public College(String name,String location,String courses[])
{
this.name = name;
this.location = location;
this.courses = courses;
faculties = new HashMap<>();
}
public void addFaculty(Faculty faculty)
{
faculties.put(faculty.getName(),faculty);
}
public void printFaculties()
{
Set<String> set = faculties.keySet();
if(set.size()>0)
{
for(String s:set)
{
System.out.println(faculties.get(s).getName());
}
}
else
{
System.out.println("No Faculties Currently Working");
}
}
public void fireFaculty(Faculty faculty)
{
faculties.remove(faculty.getName());
}
public String getName()
{
return name;
}
public String getLocation()
{
return location;
}
public String[] getCourses()
{
return courses;
}
}
If you cannot have duplicates use HashSet<Faculty> if you dont mind use a List<Faculty>.
Example:
class College {
private List<Faculty> listFactories = new ArrayList<>(); // dupes allowed
private Set<Faculty> setFactories = new HashSet<>(); // no dupes allowed
}
Check collections API.
There's a ton of ways you can do it. Probably the easiest way to handle storing a collection of objects is by using one of the Collections provided by Java. For beginners, probably the easiest one to understand is an ArrayList, which is basically an array that grows in size dynamically depending on the amount of objects in the collection.
So, as an axample, your code might be something like this:
public class College
{
private ArrayList<Faculty> faculty;
public College()
{
faculty = new ArrayList<Faculty>();
}
public void addFaculty(Faculty f)
{
faculty.add(f);
}
public void fireFaculty(Faculty f)
{
faculty.remove(f);
}
}
imho It depends what kind of services College college offers. If I were coding, I would start with:-
List<Faculy> faculties = new ArrayList<>();
....
public void addFaculty(Faculty f) {
faculties.add(f);
}
//... etc
And change to an altearnative later if needed.
public class Example {
private static class Courses {
public final String name;
public final Courses[] children;
public Courses(String name, Courses ... children) {
this.name = name;
this.children = children;
}
}
public static void main(String[] args) {
Courses courses =
new Courses("School",
new Courses("Mathematics",
new Courses("Algebra"),
new Courses("Trig"),
new Courses("Calculus"),
new Courses("Calculus 2"),
new Courses("Geometry")),
new Courses("Sciences",
new Courses("Biology"),
new Courses("Chemistry"),
new Courses("Physics"),
new Courses("Business",
new Courses("Finances",
new Courses("Accounting"),
new Courses("Accounting 1"),
new Courses("Accounting 2"),
new Courses("Administration",
new Courses("Economics"),
new Courses("Business Studies"),
new Courses("Administration 1"),
new Courses("Accounting"))),
new Courses("Physical Education"))));
System.out.println(find(courses, "Economics", courses.name));
public static String find(Courses courses, String name, String currentPath) {
if((courses.name).equals(name)){
System.out.println(currentPath);
return currentPath + " / " + name;
}
else{
//System.out.println(currentPath);
for(Courses child:courses.children){
currentPath += " / " + child.name;
find(child, name, currentPath);
}
}
return currentPath + " / " + name;
}
}
So this is the code that I have acquired. I'm trying to determine what the right thinking pattern should be when coding this find courses method. This is an array but I'm thinking of it in like a tree like manner and trying to find the answer. IS that something you guys would do too? I'm trying to find a path like this School / Business / Administration / Economics. But either I'm getting the whole path or it's iterating through the whole thing. Also, what's the approach you guys will take to accomplish this. I wrote a recursive method to achieve this, but its not working out.
Thanks, for your help
CC
Thinking about it as a tree is obviously the way to go, as it is indeed a tree.
It might help you to think what you expect the method to do if the current value of courses was the parent of the node you want. That is in your case, if it's the Administration node. In your current implementation, you will iterate over all the children, never realizing you found the correct child!
As another hint, you would generally in recursion want to do something with the result of the recursive call. In your code, you call find(child, name, currentPath) and then you do nothing with the result!
Hope these hints help you.
Your question contains some opinion-based (sub)questions. These we cannot answer, but we can help with your recursive algorithm.
The if branch of your find method seems alright. It enters that branch when an exact match occurs. The problem is in your else branch, where you need recursion to keep looking in the children courses.
Note that your method declaration returns a String.
public static String find(Courses, String, String)
And note that, when you recursively call this function, you are ignoring its return value, rendering the recursive call useless.
for (Courses child: courses.children) {
currentPath += " / " + child.name;
find(child, name, currentPath); // <-- this return value is being ignored!
}
Start by assigning the return value of the recursive search to some variable, and define a return value for when the search doesn't find the provided name (you will not find Biology under Administration, for instance). I'll assume that an empty String means the search didn't find the course.
String result = find(child, name, currentPath);
if (!result.isEmpty()) {
// it has been found
}
Finally, note that you are changing the value of the currentPath variable on each iteration, by appending to it. That will result in erroneous paths, if the name is found after the first iteration. Assign that temporary path, for that iteration, to another variable.
I would do something like this
Course.java
public class Course {
private Course parentCourse;
private String name;
public Course(String name){
this.setName(name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Course getParentCourse() {
return parentCourse;
}
public void setParentCourse(Course parentCourse) {
this.parentCourse = parentCourse;
}
}
Courses.java
public class Courses {
private List<Course> courses;
public Courses(){
}
public List<Course> getCourses() {
return courses;
}
public void setCourses(List<Course> courses) {
this.courses = courses;
}
}
Main
Courses courses = new Courses();
List listCourses = new ArrayList<Course>();
Course generalMaths = new Course("General Maths");
Course linAlgebra = new Course("Linear Algebra");
linAlgebra.setParentCourse(generalMaths);
listCourses.add(generalMaths);
listCourses.add(linAlgebra);
courses.setCourses(listCourses);
Find path
for(Course course : courses.getCourses()){
StringBuffer coursePath = new StringBuffer();
coursePath.append(course.getName());
while(course.getParentCourse() != null){
course = course.getParentCourse();
coursePath.append(" | "+course.getName());
}
System.out.println(coursePath);
}
I hope this isn't too amateurish for you guys but I'm having a hard time creating a small text-based game in Java using objects. So far I've wrote classes for Player, Item(this will be for later use, for now I have simpler goals), Room, Inventory(again, for later use) and the Main Class. What should I use to keep track of my location? I want to go through locations back-and-forth like in Zork (example go north, go south etc.) I thought about using an ArrayList that would contain every location, but again this stumbles me even more. What I wrote so far:
class Player{
//int healthPoints; for later use
private String playerName;
public void setPlayerName(String playerNameParam)
{
playerName=playerNameParam;
}
public String getPlayerName(){
return playerName;
}
}
class Item{
private String itemName;
public void setItemName(String itemNameParam)
{
itemName=itemNameParam;
}
public String getItemName()
{
return itemName;
}
}
class ExitRoom{
}
class Room{
private String roomName;
public void setRoomName(String roomNameParam){
roomName=roomNameParam;
}
public String getRoomName(){
return roomName;
}
private String roomDescription;
public void setRoomDescription(String roomDescriptionParam){
roomDescription=roomDescriptionParam;
}
public String getRoomDescription(){
return roomDescription;
}
}
class Inventory{
private ArrayList<Item> items= new ArrayList<Item>();
public boolean findItem(String itemToFind)
{
for(int i=0;i<items.size();i++){
if(items.get(i).getItemName()==itemToFind){
return true;
}
}
return false;
}
}
public class Main {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
Player player = new Player();
boolean gameRunning=true;
while(gameRunning){
System.out.println("Welcome to TextBasedGamev1!"
+ "Before beginning, please enter your name");
String name=scanner.nextLine();
player.setPlayerName(name);
Room forestWelcome=new Room();
Room forestSouth=new Room();
Room forestNorth=new Room();
Room abandonedHouse=new Room();
}
Any help is really appreciated!
A possible approach (not necessarily the best) would be to store in each room the connections to other rooms. For example:
enum Direction {
NORTH, SOUTH, EAST, WEST;
}
class Room {
private Map<Direction, Room> connections;
...
}
Generally the aproach is using a matrix with each cell and a Point to mark the position of the player, for example
Class Map {
private Room[][] matrix;
private Player player;
...
}
class Player{
private Point position;
....
}
Text adventures are actually state machines.
You might want to look at the 3 free chapters of the book I've been writing on Artificial Intelligence in C# for Games, as it covers this and Java and C# are quite similar.
http://unseenu.wikispaces.com/Game+AI+in+C-Sharp
I've been working on a game, and in the game I'm a summoner that has tamed monsters (much like pokemon).
What I want to do , is have a backpack of 5 tamed monsters, of which I can spawn 1 at a time.
Someone recommended me to use enums (I can't contact that person anymore :(), so I've been looking at a few enum tutorials and examples, and I can't figure out how this would help me.
Let us say that the enum would look like this :
public enum TamedMonsterStats {
ELF(0,"res/siren_monster_girl_sprite_by_tsarcube-d52y2zu.png",0,100);
DRAGON(0,"res/dragon.png",0,100);
private int haveit;
private String photoname;
private int typeOfDamage;/*
* 0: dark
* 1: light
* 2:
*/
private int HP;
TamedMonsterStats(int haveit,String photoname,int typeOfDamage,int HP){
this.haveit = haveit;
this.photoname = photoname;
this.typeOfDamage = typeOfDamage;
this.HP = HP;
}
public int getHaveIt(){
return haveit;
}
public String getPhotoName(){
return photoname;
}
public int getTypeOfDamage(){
return typeOfDamage;
}
public int getHP(){
return HP;
}
public void setHp(int hp) {
HP = hp;
}
}
This would kind of work, but as daveychu pointed out, this makes it impossible for me to have 2 instances of the same creature, so my idea was to have an enum backpack with monster1,monster2,monster3,monster4,monster5 , and then filling them with the values dynamically, but I feel like doing this means I shouldn't be requiring enums at all, is this true?
You can add a setter method on your enum:
public void setHp(int hp) {
HP = hp;
}
However, I'm a bit wary of your use of enum. In this situation, only one "DRAGON" instance could exist at any time so I wonder what you would do if the user wants to have more of them or if the enemy has one at the same time.
Your typeOfDamage on the other hand is an excellent candidate for an enum:
public enum DamageType {
DARK,
LIGHT,
NORMAL
}
You can then use this enum:
ELF(0, "res/siren_monster_girl_sprite_by_tsarcube-d52y2zu.png", DamageType.DARK, 100),
DRAGON(0, "res/dragon.png", DamageType.LIGHT, 100);
private DamageType typeOfDamage;
TamedMonsterStats(int haveit, String photoname, DamageType typeOfDamage, int HP) {
this.typeOfDamage = typeOfDamage;
}
public DamageType getTypeOfDamage() {
return typeOfDamage;
}
It makes it a lot more readable than having to pass some random integers.