Here is the exact instruction on what my professor has asked me to do:
Write a constructor with two parameters for int year and String player.
Use internal method call to setDetails to initialize the fields.
I have the class so far like this:
public class Card
{
private int year;
private String player;
public Card(String player, int year)
{
}
}
Not sure what the internal method call is, I have looked on the internet and StackOverflow and have not found anything that has benefited me. Any help is appreciated.
Thank you,
A first year programming student.
You need a method to set the details of the card, like this:
private final void setDetails(int year, String player) {
this.year = year;
this.player = player;
}
And then in the constructor, you can call setDetails(year, player).
Based on your statement here is the code that you 're asking for:
public class Card {
private int year;
private String player;
public Card(String player, int year) {
setDetails(player,year);
}
/*i'm making it public in case you want to call the setter directly
somewhere and final since i call an overridable method in the constructor*/
public final void setDetails(String player,int year) {
this.player=player;
this.year=year;
}
}
Related
My current problem is that I am assigned to created a program that should within the private fields assign tasks[] an array of task. Then within the constructor, that creates the task[] array, giving it the capacity of INITIAL_CAPAITY, and setting numTasks to zero.
I am new and confused on I can tackle this problem
I have tried declaring it within the constructor but there has been no luck.
Task.java
public class Task {
private String name;
private int priority;
private int estMinsToComplete;
public Task(String name, int priority, int estMinsToComplete) {
this.name=name;
this.priority=priority;
this.estMinsToComplete = estMinsToComplete;
}
public String getName() {
return name;
}
public int getPriority() {
return priority;
}
public int getEstMinsToComplete() {
return estMinsToComplete;
}
public void setName(String name) {
this.name = name;
}
public void setEstMinsToComplete(int newestMinsToComplete) {
this.estMinsToComplete = newestMinsToComplete;
}
public String toString() {
return name+","+priority+","+estMinsToComplete;
}
public void increasePriority(int amount) {
if(amount>0) {
this.priority+=amount;
}
}
public void decreasePriority(int amount) {
if (amount>priority) {
this.priority=0;
}
else {
this.priority-=amount;
}
}
}
HoneyDoList.java
public class HoneyDoList extends Task{
private String[] tasks;
//this issue to my knowledge is the line of code above this
private int numTasks;
private int INITIAL_CAPACITY = 5;
public HoneyDoList(String tasks, int numTasks, int INITIAL_CAPACITY,int estMinsToComplete, String name,int priority) {
super(name,priority,estMinsToComplete);
numTasks = 0;
tasks = new String[]{name,priority,estMinsToComplete};
//as well as here^^^^^^^^
}
My expected result is to be able to print out the list through honeydo class. I need to manipulate the code a bit more after adding a few other methods.
Your problem is that your constructor parameter tasks has the same name as that field of your class.
So you assign to the method parameter in your constructor, not to the field. And luckily those two different "tasks" entities have different types, otherwise you would not even notice that something is wrong.
Solution: use
this.tasks = new String...
within the body of the constructor!
And the real answer: you have to pay a lot attention to such subtle details. And by using different names for different things you avoid a whole class of issues!
Also note: it sounds a bit strange that a class named Task contains a list of tasks, which are then strings. The overall design is a bit weird...
I tried searching everything but i didn't find any solution. One question is similar but no one has answered it properly. Moving to the question, I have a class which has room entity annotation and the same class extends another class (which is Library class). Now when i run the project I get an errors like Error:Cannot find getter for field. Library's super class making issue here as it works when i remove it. Please tell me how can i make room work with subclass as entity extending super class. Thank you for your time.
#Entity(tableName = "event")
public class EventDetails extends ParentEntity implements Parcelable{
#PrimaryKey(autoGenerate = true)
int id;
String name;
Calendar startDay = Calendar.getInstance();
Calendar endDay = Calendar.getInstance();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Calendar getStartDay() {
return startDay;
}
public void setStartDay(Calendar startDay) {
this.startDay = startDay;
}
public Calendar getEndDay() {
return endDay;
}
public void setEndDay(Calendar endDay) {
this.endDay = endDay;
}
public void setName(String name) {
this.name = name;
}
#Override
public String getName() {
return name;
}
}
public class ParentEntity {
private Calendar mDay;
public Calendar getmDay() {
return mDay;
}
public void setmDay(Calendar mDay) {
this.mDay = mDay;
}
}
This seems to be mainly a naming problem: after changing the field name from mDay to just day and renaming the setter/ getter accordingly, everything compiles.
It looks like the method names which Android Studio generates from mDay are not the ones which Room is looking for.
Since you are in a position to use different field names in the parent class, this looks like the best solution.
If it is not possible to change the library, it is especially not possible to mark fields in the library class with Ignore, so one can't fix the problem by inserting an intermediate class into the inheritance hierarchy. (I tried using a Constructor for EventDetails with the private field as argument but this too did not work)
So in this case I think your best option would be not to try to extend from the library class (but maybe from some "surrogate parent" class) and to bridge the gap to the library class with the help of some factory class.
I have this class and need to know which constructor is needed to create an object that may immediately use all its methods without error
public class Robot {
private boolean fuelEmpty = true;
private int roboID;
private String greeting;
private String securityProtocol;
//insert robot constructor here
public void destroyAllHumans(){
while (fuelEmpty == false) {
//robot begins to destroy all humans
}
}
public int getRoboID(){
return roboID;
}
public void greet(){
System.out.println(greeting);
}
public void setSecurityProtocol(String proto){
securityProtocol = proto;
}
}
For example should look like this:
public Robot(int id, String greet) {
roboID = id;
greeting = greet;
}
or this:
public Robot(int id, String greet) {
roboID = id;
greeting = greet;
fuelEmpty = false;
}
or:
public Robot(boolean full, int id, String greet, String proto) {
roboID = id;
greeting = greet;
fuelEmpty = full;
securityProtocol = proto;
}
Which of these (or something else different) is needed so that all the other methods can run without an error?
You can overload the constructor as much as you need, the important thing is
the object gets properly instantiated after you create a new one...
a way can be:
public Robot() {
this(false, 0, "", "");
}
public Robot(int id) {
this(false, id, "", "");
}
public Robot(boolean fuelEmpty, int roboID, String greeting, String securityProtocol) {
this.fuelEmpty = fuelEmpty;
this.roboID = roboID;
this.greeting = greeting;
this.securityProtocol = securityProtocol;
}
so look how all other constructors will at the end call internally the
public Robot(boolean fuelEmpty, int roboID, String greeting, String securityProtocol)
that will give you the waranty that no matter which constructor is invoked, the Robot is fully created and can invoke all those methods without crashing
The solution works like this:
you look at each of your methods
you check which fields each method is using
you check more closely, if the method breaks when that field has its default value (like null for Objects, or false for booleans)
When you do that for all methods, you get a list of those fields that you need to initialize somehow. Then you could go forward and define a corresponding constructor.
But of course, that is the wrong approach.
The real answer goes like this: you don't put fields into a class because you can. You add them because they are required so that this class can implement the requirements (responsibilities) that you want it to implement. Meaning: you focus on the methods that your class should provide. Then you clarify which fields you need in order to implement these methods.
In other words: you have exactly those fields in your class that your class needs. If you have fields in there that go unused - then you get rid of them.
I am having trouble returning my static private variable personCount. This variable simply counts the amount of people i add into my program, in my constructor for Person i set it so every time a person was entered, personCount incremented by 1. I have also created a getPersonCount method which simply returns the int value of personCount.
My problem is that when trying to implement this method in my test file, I am unsure on how to call the method, and get the value of personCount logged to the output.
I'm not sure if i am a million miles away or a small syntax error away, so any help would be much appreciated!
My Person constructor:
public Person(String foreName, String surName, int age,
double height, String gender)
{
this.foreName = foreName;
this.surName = surName;
this.age = age;
this.height = height;
this.gender = gender;
personCount = personCount +1;
}
My getPersonCount method:
public int getPersonCount()
{
return personCount;
}
My attempt to call the method in my test drive:
System.out.println(getPersonCount());
Please let me know if any more code is needed.
Try this, make your method definition in class Person like:
public static int getPersonCount() { //<-- note the static modifier
return personCount;
}
To invoke it:
System.out.println(Person.getPersonCount());//<-- use class name, if your using this method outside the class
You have two choices:
public static int getPersonCount() {
return personCount;
}
with the corresponding call:
Person.getPersonCount();
OR:
public int getPersonCount() {
return personCount;
}
and the corresponding call:
myPersonInstance.getPersonCount();
So in the last case, you deal with a Person instance.
public static int getPersonCount(){
return personCount;
}
Then invoke above method
Person.getPersonCount();
This is a question from an exam past paper. I have completed the question and it works. However, i feel my implementation may be weak e.g. my use of static throughout the Gregorian class.
I was given three methods to write in any way i saw fit (in the Gregorian class) given a scenario for each. Was I right in using static on the three methods in the Gregorian class.
Also the day, month and year fields are meant to be immutable, is setting them as private enough? (once they are created the field values cannot be changed)
public class Date {
private int day;// needs to be immutable?
private String month;// needs to be immutable?
private int year;// needs to be immutable?
public Date(int theDay, String theMonth, int theYear) {
this.day = theDay;
this.month = theMonth;
this.year = theYear;
}
public int getDay() {
return day;
}
public String getMonth() {
return month;
}
public int getYear() {
return year;
}
}
public class Gregorian {
public static Date d;
public static boolean leapYear(){
if(d.getYear() %400==0 || (d.getYear()%4==0 && d.getYear()%100!=0)){
return true;
}else{
return false;
}
}
public static int getGregorianDateNumber(){
int a = (d.getYear()*384)*(32+d.getDay());
return a;
}
public static int getISO8601Date(){
int b = (d.getYear()*367)+d.getDay();
return b;
}
public static void main (String[] args){
d = new Date(9, "June", 8);
System.out.println(getGregorianDateNumber());
System.out.println(getISO8601Date());
System.out.println(leapYear());
}
}
Instead of the static methods and the static field d make them all non-static.
public class Gregorian {
private final Date d;
public Gregorian(Date d_) {
this.d = d_;
}
public boolean isLeapyear() {
... // implemented as above
}
... // Other methods as above, but all non-static.
}
And main as follows:
public static void main (String[] args){
Date d = new Date(9, "June", 8);
Gregorian g = new Gregorian(d);
System.out.println(g.getGregorianDateNumber());
System.out.println(g.getISO8601Date());
System.out.println(g.leapYear());
}
Strings are by default immutable.
private int day;// needs to be immutable?
private int year;// needs to
are not immutable fields as you defined. Their state can change. Make them final.
NOTE: Making a reference final doesn't mean object state can't be changed (In your case this note is irrelevant, because you are not referencing objects).
I'll agree with thinksteep - adding "final" to your fields will help keep them from being changed. Not having setters reinforces this.
In addition, I want to point out that
private String month;// needs to be immutable?
can be created as anything, from "January" to "Pie". If I may suggest, change it to an enum and establish the allowed values for months.
public enum MonthName {
JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC;
}
Change your Date class to the following:
private final int day;
private final MonthName month;
private final int year;
public Date(int theDay, MonthName theMonth, int theYear) {
this.day = theDay;
this.month = theMonth;
this.year = theYear;
}
both day and year are primitives and There is already immutable version of int available which is Integer you can make use of that.
Second thing is, rather having a static reference to Date in Gregorian, pass the Date as an argument to each of the static methods. You can assure the thread safety then.