Cannot invoke " " because array is null - java

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.

Related

How to print every element in array in loop if with different types of element?

I have this phone class:
public class Phone {
private int id;
private String brand;
private String model;
private int cameraResolution;
public Phone(int id, String brand, String model, int cameraResolution) {
this.id=id;
this.brand=brand;
this.model=model;
this.cameraResolution= cameraResolution;
}
public void showDetails() {
System.out.println("id "+ this.id);
System.out.println("Marka to "+ this.brand);
System.out.println("Model to "+ this.model);
System.out.println("Rozdzielczosc aparatu to " + this.cameraResolution);
}
and this main class
import java.util.ArrayList;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Phone galaxy= new Phone(1, "Samsung","Galaxy",12);
Phone lumia= new Phone(2, "Nokia","Lumia",13);
Phone pixel= new Phone(3, "Google","Pixel",14);
galaxy.showDetails();
//String[] phones = new String[3];
//phones[0]="galaxy";
//phones[1]="lumia";
//phones[2]="pixel";
Phone[] phones = new Phone[3];
phones[0]= galaxy;
phones[1]= lumia;
phones[2]= pixel;
// dont work System.out.println(Arrays.oString(phones));
}
}
I want to write a loop, that will call the phone.showDetails() method from the phone's array, but I can't find a way to do it. There's a problem with data type conversion or sth.
I want to achieve a loop, that will call:
galaxy.showDetails, then lumia.showDetails() and pixel.showDetails();
You can loop through every element and print its details.
for (Phone phone: phones){
phone.showDetails();
}
Your big issue is your phone class doesn't override toString(), so all youre going to see is memory address space. Do something like this:
#Override
public String toString() {
return "Phone [id=" + id + ", brand=" + brand + ", model=" + model + ", cameraResolution="
+ cameraResolution + "]";
}
As for looping through, there are lots of ways you can do this, but the easiest:
for (Phone phone : phones) {
System.out.println(phone);
}

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

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.

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.

Java Static constructor not working

Here is my code
class Bomb {
static String description = "bomb description";
static int id = 1;
private String name;
private int size;
public static void Bomb() {
id++;
System.out.println(" " + description + " " + id);
}
public void setName(String name) {
this.name = name;
}
public void setSize(int size) {
this.size = size;
}
public void printout() {
System.out.println(" " + name + size);
}
}
public class array {
public static void main(String args[]) {
Bomb.Bomb();
Bomb detenator = new Bomb();
Bomb destroyer = new Bomb();
destroyer.setName("hr4");
destroyer.setSize(43);
detenator.setName("m1s");
detenator.setSize(34);
detenator.printout();
destroyer.printout();
}
}
I want the description to print with each bomb object. but the description prints by itself.
any one got any idea how to fix that?
also please suggest any alternative ways I could've written this code, but don't make it to complicated. i just started learning java so i probably wont understand complex stuff.
I short, there are no "static constructors".
You may want something that references a static member, like this:
public Bomb() {
id++;
System.out.println(" " + Bomb.description + " " + id);
}
Please go over the Java tutorial of constructors:
Constructor declarations look like method declarations—except that they use the name of the class and have no return type.
Your definition of constructor is completely messed up.
As #Reut Sharabani mentioned there is no something like static constructor. You are using constructors to initiate object of a class. And static let you use method just by calling ClassName.staticMethod() without creating object of the class (one ruling out another). If static constructor would exist you would be able to write something like, for example, ClassName.ClassName() which make no sense.
Constructors are not returning any value, so declaring them as void is an error. Again constructor is used to initialize your object with some values (but unnecessary)

How to make a record of multiple data types in java?

(using Netbeans)
I want to make something with an index like an array does, that when called will return multiple pieces of information which were previously inserted by the user.
e.g
name = Luke;
age = 20;
favouriteColour = red;
I have tried multiple arrays, maps/hashmaps (please someone explain these aswell, I have no clue), and despite it kind of working, it's like I've just thrown spaghetti at the screen.
Any ideas?
I think what you want is an Object, just create a class yourself. For example:
public class Person
{
private String name;
private int age;
private Color favoriteColor;
public Person(){
// perhaps add some defaults here
}
public void setName(String n){
name = n;
}
public String getName(){
return name;
}
public void setAge(int a){
age = a;
}
public int getAge(){
return age;
}
public void setFavoriteColor(Color c){
favoriteColor = c;
}
public Color getFavoriteColor(){
return favoriteColor;
}
}
In your main app you can then create this Object like so:
Person person = new Person();
Store the user inputs in it. So when the user adds a name:
person.setName(nameThatWasInputtedByTheUser);
You can store all of these UserInputContainers in a list:
ArrayList<Person> list = new ArrayList<Person>(); // or "new ArrayList<>();" when you use Java 8.0+
Then at the end you can get all this again like so:
System.out.println("Person at index " + index);
Person currentPerson = list.get(index);
System.out.println("Name: " + currentPerson.getName());
System.out.println("Age: " + currentPerson.getAge());
System.out.println("Color: " + currentPerson.getColor());

Categories

Resources