Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
class Persons {
private String name;
public Persons(String name) {
this.name = name;
}
public boolean equal(Persons p) {
return p.name.equals(this.name);
}
}
public class pa {
public static void main(String ar[]) {
Persons a = new Persons("Roman");
boolean max;
max = a.equal(new Persons());
System.out.print(max);
}
}
you do not have default constructor in your Persons class
change
max = a.equal(new Persons());
to
max = a.equal(new Persons("someValue"));
or provide default constructor
You only have 1 constructor in class Person
public Persons(String name) {
this.name = name;
}
But, you create a new instance of Person like this:
max = a.equal(new Persons());
Solutions:
Create a default constructor : public Persons () { }
Use existing constructor : max = a.equal(new Persons(""));
Always add a default constructor when providing a parametrized one.
class Persons {
private String name;
public Persons(){
}
public Persons(String name) {
this.name = name;
}
public boolean equal(Persons p) {
return p.name.equals(this.name);
}
}
You don't have a default constructor for Person,
max = a.equal(new Persons("")); // <-- need a String.
Also, you should name your method equals(), because that's the Object method;
#Override
public boolean equals(Object p) {
if (p instanceof Persons) {
return this.name.equals(((Persons) p).name);
}
return false;
}
also you do not have constructor like this :
public Persons() //no parameter
{
this.name = name;
}
so you can't create a new instance of Persons (wow! too many person.) using the above constructor.
Issue is here
Persons a = new Persons("Roman");
boolean max;
max = a.equal(new Persons()); // Persons class don't have no-argument construtor
You have to change this to
max = a.equal(new Persons("yourValue"));
Or you can add no argument constructor to Persons class.
public Persons(){
}
Related
String answer = question1?.question2?.answer
Is there a way (preferably in-built) to get the property of an object where both the following scenarios are covered:
If the object is null, return a null value for the attribute.
Returns null for an attribute if it doesn't exist in the object.
To top this, is there a way to chain such get operations for deeply nested attributes?
Java doesn't however Groovy does. When writing Groovy you can mix java right in with it. In Groovy you can do println company?.address?.street?.name
it's possible to obtain "similar" behavior(chain) but just with custom code ( not being something inbuild)
public class TestChain
{
public static void main(String args[])
{
TestChain tc = new TestChain();
Person p = tc. new Person();
p.setName("pName").getMsg().setAge(10).getMsg();
}
class Person
{
String name;
int age;
public Person setName(String name)
{
this.name = name;
return this;
}
public Person setAge(int age)
{
this.age = age;
return this;
}
public Person getMsg()
{
System.out.println(this);
return this;
}
public String toString()
{
return "name="+name+",age="+age;
}
}
}
Output:
name=pName,age=0
name=pName,age=10
Basically methods to be chained need to return current instance.
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 am currently learning Java with eclipse for my computer science course, and I need some assistance trying to figure out how to fix the error that is currently showing.
package sec4Les2;
public class RoseDS4L2Person {
//creating the variables
public String name = "Uma Thurman";
public int Age = 0;
//constructor
public RoseDS4L2Person()
{
}
public String getname()
{
//will return first name
return name;
}
public int getAge()
{
//will return age
return Age;
}
public void setAge(int Age)
{
//will set age to int
this.Age = Age;
}
}
And here is the running code:
package sec4Les2;
public class RoseDS4L2ManagingPeople {
public static void main(String[] args) {
//runs information in first class file
RoseDS4L2Person p1 = new RoseDS4L2Person("Arial", 37);
RoseDS4L2Person p2 = new RoseDS4L2Person ("Joseph", 15);
if(p1.getAge()==p2.getAge())
{
System.out.println(p1.getname()+" is the same age as "+p2.getname());
}
else
{
System.out.println(p1.getname()+" is NOT the same age as "+p2.getname());
}
}
}
It says there are no errors on the first one, but the second one has errors on the p1/p2 lines. How can I fix this error? thank you!
You should have a constructor for RoseDS4L2Person accepting a string and a number, like so:
public RoseDS4L2Person(String name, int age)
{
this.name = name;
this.Age = age;
}
This will allow you to create an instance of the class passing a name and an age as parameters.
You need to add this code to your class. Basically, a constructor was missing in your class. Also note that by convention, member variables start in lowercase. So your Age should really be age.
Another thing is, you have kept name as constant. Probably you want to remove "Uma Thurman". If you want to keep that as default name for all objects where name is not specified at initialization time, you would want to add that in the constructor. *
public class RoseDS4L2Person
{
// other lines ....
RoseDS4L2Person(String name, int age) {
this.Age = age;
this.name = name;
}
}
*
Something like this:
public class RoseDS4L2Person
{
private static final String UMA_THURMAN = "Uma Thurman";
// other lines ....
RoseDS4L2Person( int age) {
this.Age = age;
this.name = UMA_THURMAN;
}
}
The error is popping up because you have created objects with a non-existing constructor.Making objects with the default constructor or creating a constructor
which can accept the arguments you pass should do the trick.
Happy Coding
This question already has answers here:
Setter methods or constructors
(10 answers)
Why use getters and setters/accessors?
(37 answers)
Closed 6 years ago.
In the below code I've already declared that room = r; subject = s; and time = t; in the user defined constructor, so why is it necessary to do so again in set methods, my lecturer specifically asked that we add set methods for the room subject and time but it's redundant code as when I comment it out it still works. Do you only need to include set methods when there is no used defined constructor? What could be the advantage of having them set methods there?
class LectureTest{
public static void main (String [] args){
Lecture l1 = new Lecture(140, "Comp", 5);
l1.display();
Lecture l2 = new Lecture(280, "Sports", 3);
l2.display();
Lecture l3 = new Lecture(101, "Business", 5);
l3.display();
Lecture l4 = new Lecture(360, "Shooting", 4);
l4.display();
Lecture l5 = new Lecture();
l5.display();
}
}//end of LectureTest
class Lecture{
private int room;
private String subject;
private int time;
Lecture(int r, String s, int t){
room = r;
subject = s;
time = t;
}
Lecture(){}
public void setroomNumber(int r){
room = r;
}
public void setSubject(String s){
subject = s;
}
public void setTime(int t){
time = t;
}
public int getroomNumber(){
return room;
}
public String getSubject(){
return subject;
}
public int getTime(){
return time;
}
public void display(){
System.out.printf("\n" + "Room Number: " + getroomNumber() + "\n" + "Subject: " + getSubject() + "\n" + "Time " + getTime() + "\n");
}
}
The constructor "initializes" your values.
Let's say you have...
public class Person {
public String name;
public int age;
public Person (String name, int age) {
this.name = name;
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public String toString() {
String str;
str = "My name is "+name+" and I am "+age+" years old!";
return str;
}
}//End of Person
public class Main {
public static void main(String [] args) {
Person person = new Person("Bob", 15);
System.out.println(person.toString());
System.out.println("Switching my name...");
person.setName("Joe");
System.out.println(person.toString());
}
}//End of main
You see the difference? You should use the constructor if you want to create a new instance of the object. This way, you can set all the fields of the object at once and not need to call 490832490 setters (in this case, one for name and one for age...). You then can use the setter approach when you want to change the value of a field, PRIOR TO the object been created.
I DID ALL THIS ON THIS FORUM SO I MIGHT HAVE SYNTAX ERRORS SO CAREFUL...DIDN'T USE AN IDE IF YOU WANT TO TEST IT
The set methods make your object mutable. If you don't have the set methods and your variables are private then the Object will be immutable. You won't be able to change the values after it is constructed...If the values need to change you would have to create a new Object.
"Setters" allow you to modify private attributes of your object after instantiating. For example:
Lecture l1 = new Lecture(140, "Comp", 5);
//Since "room" is private you can't write l1.room = 4
//and have to use the setter method instead:
l1.setroomNumber(4);
l1.display();
They are also very useful if you want to do something if an attribute changes.
Let's assume you are using Observers, then you could call notifyObservers() or setChanged() in your setter method and never have to worry about these methods not getting called if your attribute changes.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
So. I got a mission from my teacher to make a program that manages different students. The program will hold the name, education, information and points.
You will have the option to:
Add new students
Change education and information
Manage points
Making new students is not a problem, but managing education, info and points for specific students is the hard part, that's where I need your help. My main.java does not contain anything for now.
Student.java
package student;
public class Student {
String namn;
String program;
String info;
int points;
public void managePoints(){
}
public void changeProgram(){
}
public void changeInfo(){
}
}
Main.java
package student;
public class main {
public static void main(String[] args) {
}
}
According to the comments, I guess the three methods in your class are supposed to change the points, program and info of the student to a desired value. In Java, we call these setters.
You should rename your methods to setPoints, setProgram and setInfo. It's a pattern, you know.
Next, how are you going to know the "desired" value of those fields? You might say, I get them from the text boxes in the methods. But a better approach would be to get the values from another method and pass the value to the setters as a parameter.
To add a parameter to your methods, add a variable-like thingy in the brackets of the method declaration:
public void setPoints (int p)
And for the setInfo
public void setInfo (String i)
And so on.
In the method bodies, you set the fields to the parameters. E.g. In the setInfo method you write
info = i;
I think you can figure out the others.
Now how do you use these methods? For instance, suppose you have a student variable called student. And you got the info of him/her and stored it in a string variable called studentInfo. You can set the student variable's info to studentInfo by
student.setInfo (studentInfo);
Or if you don't want to use a variable, you can just use a string literal.
student.setInfo("this is my info. Blah blah blah");
I don't exactly know what do you want to actually do but your Student class (if I think correctly what you will need) should look more like this:
public class Student {
private String name; // private because you don't want anyone to interact with the variable too much.
private String program;
private String info;
private int points;
public Student( String name, String program, String info, int points ) { // contructor with variables to initialize. You can remove some of the variables if you do not consider they should be here.
this.name = name;
this.program = program;
this.info = info;
this.points = points;
// without `this` you would change parameter's value to itself which isn't what you want.
}
public String getName( ) { // getter because I guess you would like to know students name
return name;
}
public int getPoints( ) {
return points;
}
public void addPoints( int points ) { // setter so you can modify points
this.points += points;
}
public String getProgram( ) { // same as getName
return program;
}
public void setProgram( String program ) {
this.program = program;
}
public String getInfo( ) {
return info;
}
public void setInfo( String info ) {
this.info = info;
}
}
But how to use these methods? You use them as the example below shows
Student s1 = new Student("Abc Xyz", "IT", "Some informations", 12);
Student s2 = new Student("Cba Zyx", "Some other program", "Some more informations, 0);
s2.setInfo( s1.getInfo( ) );
s1.setPoints(1234);
s2.setProgram("Axbzcy");
Getter is a method which returns (most likely) private variable's value.
Setter is a method which sets private variable's value to another value which is passed as a parameter to the method.
Final code:
package student;
// The student class definition
public class Student {
private String name;
private String address;
private String info;
private String kurs;
private int points;
// Constructor
public Student(String name, String address, String info, String kurs, int points) {
this.name = name;
this.address = address;
this.points = points;
this.kurs = kurs;
this.info = info;
}
// Public getter for private variable name
public String getName() {
return name;
}
// Public getter for private variable address
public String getAddress() {
return address;
}
public String getInfo() {
return info;
}
public int getPoints() {
return points;
}
// Public setter for private variable address
public void setAddress(String address) {
this.address = address;
}
public void setPoints(int points){
this.points = points;
}
public void setInfo(String info){
this.info = info;
}
public void setKurs(String kurs){
this.kurs = kurs;
}
// Describe itself
public String toString() {
return name + ", Adress: " + address + ", Info: " + info + ", Kurs: " + kurs + ", Poäng: " + points +" ";
}
}
Main
package student;
// A test driver program for the Student class
public class main {
public static void main(String[] args) {
Student ArHa = new Student("A H", "Jysgaan 61", "ADHD", "Teknik", 5);
ArHa.setPoints(10);
ArHa.setKurs("TEINF");
System.out.println(ArHa);
Student DaSk = new Student("Dael Sklbr", "Fegea 65", "Svart", "Teknik", 5);
DaSk.setInfo("Riktigt svart");
System.out.println(DaSk);
Student FaMe = new Student("Falafel Medusa", "Fågel 123", "Maten", "Kock", 123);
System.out.println(FaMe);
}
}
Thank you everyone for the help.