JAVA Created two objects of each class with complete data using a constructor but getting an error - java

I'm trying to create two objects of each Man and Woman class with complete data using a constructor, with constructor that have all possible parameters.
I'm getting an error stating :
"invalid method declaration; return type required".
My code :
public class Solution {
public static void main(String[] args) {
Man man1 = new Man();
System.out.println(man.name + "" + man.age + "" + man.address);
Man man2 = new Man();
System.out.println(man.name + "" + man.age + "" + man.address);
Woman woman1 = new Woman();
System.out.println(woman.name + "" + woman.age + "" + woman.address);
Woman woman2 = new Woman();
System.out.println(woman.name + "" + woman.age + "" + woman.address);
//write your code here
}
private String name = "Mark";
private int age = 23;
private String address = 16527;
public Man(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
public Woman(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;//write your code here
}
}
Can someone please help me :(

Your class is named Solution which means that your constructor can be named only Solution. Create separate classes named Man and Woman and then add your constructors there.
Also, since you are creating an object using default constructor, make sure to add them too in the above mentioned classes.

In order to call new Man() or new Woman(), you need to create an empty constructor for each class. Alternatively, you can have no constructor at all in the class and let java construct the default constructor.
Based on your code, you can only initialize them via the constructor that you have create which are new Man("Mark", 23, "16527") and new Woman("Mary", 23, "16527")

May be your code will be like this:
public class Solution {
public static void main(String[] args) {
Man man1 = new Man(); // first way to create object
Man man2 = new Man("dhiraj",28,"Indore"); // second way to create object
System.out.println(man2.name + "" + man2.age + "" + man2.address);
Woman woman1 = new Woman(); // first way to create object
Woman woman2 = new Woman("dhiraj",28,"Indore"); // second way to create object
System.out.println(woman2.name + "" + woman2.age + "" + woman2.address);
//write your code here
}
}
class Man
{
private String name, address;
private int age;
public Man()
{
}
public Man(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
}
class Woman
{
private String name, address;
private int age;
public Woman()
{
}
public Woman(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;//write your code here
}
}

It seems you are new to Java. The code you've provided has a lot of mistakes.
(For ex:) Constructor should have the same name as the class
While defining an object using a constructor parameters should be passed as arguments(If not default constructor will be called) and etc. Please refer This link to get more idea about java classes and objects.

Your main problem, the cause of the error invalid method declaration; return type required is that you are putting the constructor for Man and Woman inside another (Solution) class. They should be defined in their own class. This error you're getting means that the compiler thinks there is a regular method declaration without a return type. It just thinks you made a method called Man(with some arguments) and a method called Woman (with some arguments).
Additionally, if you want that data to actually be part of the Man or Woman class, you should make sure it becomes part of those objects. You could make a constructor with those arguments or add it through setter methods later. The data won't magically appear in those objects just by constructing them with an empty constructor.

Related

Cannot invoke " " because array is null

I need to add information about 2 actors such as their name, address and age and have done so without arrays easily but it's necessary, I keep getting the error
"Cannot invoke "TestActor.setName(String)" because "actors[0]" is null
at TestMain.main(TestMain.java:5)"
This is just a test main I'm using to test it
'''
public class TestMain {
public static void main(String[] args) {
TestActor[] actor = new TestActor[2];
//Actor act1 = new Actor(" ", " ", 0);
actor[0]= ("");
actor[0].setName("Jack Nicholson");
actor[0].setAddress("Miami.");
actor[0].setAge(74);
actor[0].printAct();
}
And this is the actor class I'm using that I need to set the information from
public class TestActor {
private String name;
private String address;
private int age;
public TestActor(String s, String g, int p) {
this.name = s;
this.address = g;
this.age = p;
}
public void setName(String s) {
name = s;
}
public void setAddress(String g) {
address = g;
}
public void printAct() {
System.out.println("The actor's name is " + name + " and age is " + age + ". They live in " + address);
}
public void setAge(int p) {
age = p;
}
public String toString() {
return "The actor's name is " + name + " and age is " + age + ". They live in " + address;
}
}
I know the toString doesn't do anything there the way I have it setup just for the time being. It might be a bit of a mess and I might be in totally the wrong track. I was able to do it relatively easily wihtout using arrays but they've kinda stumped me and I'm not 100% sure on the direction to go in without maybe butchering the whole thing.
Compiler is complaining because you're not initializing TestActor object correctly. You should rather do this:
actor[0] = new TestActor("Jack Nicholson", "Miami.", 74);
actor[0].printAct();
If you don't want to do this and use setters manually, then you need to define a default constructor in TestActor:
public TestActor() { }
then you should be able to use it in your arrays like this:
actor[0] = new TestActor();
actor[0].setName("Jack Nicholson");
actor[0].setAddress("Miami.");
actor[0].setAge(74);
actor[0].printAct();
When you create TestActor[] actor = new TestActor[2];, you are creating an array of a reference type object. So, actor[0] as well as actor[1] refer null. First create TestActor and assign the objects to the array. Like:
TestActor actorOne = new TestActor("s", "g", 0);
actor[0] = actorOne;
OR
TestActor[] actor = new TestActor[2];
actor[0]= new TestActor ("Jack Nicholson", Miami.", 74);
actor[0].printAct();
It seems your problem is with initializing the Actor to an empty string instead of a TestActor object:
actor[0] = ("");
Instead try:
actor[0] = new TestActor("Jack Nicholson", "Miami.", 74);
Each TestActor needs to be instantiated so this will instantiate the TestActors and also populate the fields you want.

Why should you create a new instance of a class? [duplicate]

This question already has answers here:
What does the 'static' keyword do in a class?
(22 answers)
Closed 4 years ago.
I've been running through a few tutorials for Java, they all say to make a new variable when calling classes. Why is this? I've tested some code and it works without doing this.
I've been using python for quite a while now so I'm used to using a dynamic language.
Please see some code I've been playing around with below:
import java.util.Scanner;
class MyClass {
static String myName(String name) {
return ("Your name is: "+name);
}
static String myAge(Integer age){
return ("Your age is: "+age);
}
static String myGender(String gender){
return ("You are: "+gender);
}
}
class Test{
public static void main(String [ ] args){
Scanner ui = new Scanner(System.in);
MyClass user = new MyClass();
//Output with new variable of class - user
String input = ui.next();
String newname = user.myName(input);
System.out.println(newname);
//Output calling class directly
Integer input1 = ui.nextInt();
String newage = MyClass.myAge(input1);
System.out.println(newage);
//Output with new variable of class - user
String input2 = ui.next();
String newgender = MyClass.myGender(input2);
System.out.println(newgender);
}
}
Thanks for your time.
If everything in the class is static (as in the code you posted), then there's no need to create instances of the class. However, if the class were to have instance fields and/or methods, then the story is different. For instance, consider a class like this:
class Person {
private String name;
private int age;
private String gender;
public Person(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
String myName() { return "Your name is: " + name; }
String myAge() { return "Your age is: " + age; }
String myGender() { return "You are: " + gender; }
}
Then you could create several Person instances with different internal state and use them interchangeably in your code:
public static void main(String[] args) {
Person jim = new Person("Jim", 40, "male");
Person sally = new Person("Sally", 12, "female");
report(jim);
report(sally);
}
private static report(Person person) {
System.out.println(person.myName());
System.out.println(person.myAge());
System.out.println(person.myGender());
}
If we create any member with static keyword it get memory at once to all objects, static keyword we used when we have common properties in class and we don't want to create separate memory to all instances objects ... it doesn't need to create instance variable to call it and this static block is shareable to to all objects.... for example if we have Animal class and we want to describe 5 different type of dog's ... than we don't define color, size like properties as static ... because they all have their own different size and color.... I hope you get it

Java Exarcise. How to create a class similar to social media site?

Create and implement a class Person. A Person has a firstName and friends. Store the names of the friends as a String, separated by spaces. Provide a constructor that constructs a Person with a given name (passed through arguments) and no friends. Provide the following methods:
public void befriend(Person p)
public void unfriend(Person p)
public String getFriendNames()
public int getFriendCount()
*Hint - you can use p.name to access the name of the Person passed to a method as an argument.
Include a Tester class to make sure your Person has some friends.
How do I store the names of the friends as a String, separated by spaces. (I have to be able to input the names from the main method). I also have no idea how to get rid of already inputted name using the method "unfriend"
public class Person
{
private String firstName;
private String friendNames;
private int friendCount;
public Person(String name)
{
firstName = name;
friendCount = 0;
}
public String getFriendNames()
{
return friendNames;
}
public double getFriendCount()
{
return friendCount;
}
public void befriend(String name)
{
friendNames = friendNames + " " + name;
friendCount++;
}
public void unfriend(String name)
{
String[] parseNames = friendNames.split(name);
friendNames = parseNames[0] + parseNames[1];
friendCount--;
}
}
Main Method:
public class PersonTester {
public static void main(String[] args) {
Person p = new Person("Alex");
p.befriend("John");
p.befriend("Alice");
p.befriend("Mike");
p.befriend("Annette");
p.unfriend("Alice");
System.out.println(p.getFriendCount());
System.out.println(p.getFriendNames());
}
}
Expected output:
2
John Mike
The problems you are having with the methods using the parameter(Person p) are because you have two different variables: friendName (which exists) and name (which does not). Changing the variable friendName to name will take care of some of the errors you are receiving.
(Also the method getFriendCount() returns friendsCount, but should return friendCount (you have an extra s in there) and your assignment calls for a method called befriend, not bestFriend.)
How to delete friends:
You can delete a friend by parsing the friend out of the friendNames string and then concatenating the two resulting strings back together:
public void unfriend(String name)
{
String[] parseNames = friendNames.split(name);
friendNames = parseNames[0] + parseNames[1];
friendCount--;
}
I would suggest changing befriend and unfriends parameters to accept a String instead of a Person object. Person already has access to its own object and in your main you are trying to pass them Strings anyways. Here is what befriend should look like:
public void befriend(String name) //Changed to "befriend"
{
friendNames = friendNames + " " + name;
friendCount++;
}
Also, you only need one constructor for Person, which should look like this:
public Person(String name)
{
firstName = name;
friendCount = 0;
}
When I run your program (using these changes) I get the following output:
2.0
John Mike

What's the importance in using the set method when the attributes have already been defined in the Used Defined Constructor? [duplicate]

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.

Return a string and int

How do i return a string and an integer? say i wanted to return
students name which is an string and their mark which is an integer.
I cant do mark=mark+element+(element2+name); that creates an incompatible type.
My suggestion in this type of situation is to create a new class that holds this information. Name it for example StudentMark.
class StudentMark {
private final String name;
private final int mark;
public StudentMark(String name, int mark) {
this.name = name;
this.mark = mark;
}
public String getName() { return name; }
public int getMark() { return mark; }
}
Then in your method that has both the name and mark where you want to return, just do like so.
return new StudentMark("Samuel", 3.2);
Here you can also add any other interesting methods that you might need.
Create a class Student and return a student
class Student{
private String name;
private int mark;
//assessor+ contructors
}
you'll need to define a class for it. the class should have two attributes: a string and an int
Define a class that contains both values and return an object of that class.
create A class with priavte variables for name and marks. and override toString() method.
public class Student{
private int marks;
private String name;
//provde setters and getters for marks and name
public String toString(){
return getName()+getMarks();
}
}
In your Student class, you can have a method:
public String printNameAndGrade() {
return "Name: " + this.getName() + "\n " + "Grade: " + this.getGrade();
}
and then call it with a Student object reference:
Student st1 = new Student("Gabe Logan", 97);
System.out.println(st1.printNameAndGrade()); //use `println` method to display it.
You can use a two element Array or List and put the values in there. Unfortunately this looses all type Information.
You can use a Map which keeps the type information, but might be confusing because you would expect an arbitrary number of entries.
The cleanest option is to create a simple class with the two elements.

Categories

Resources