Why does a method call with null value raise a NullPointerException when the costructor call does not and how do I fix it in this case? [closed] - java

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 2 days ago.
Improve this question
I have a class Student where I have a constructor and two methods.
package myclasses;
import java.util.Random;
public class Student{
private String firstName = "No name", lastName = "No name", titleOfBachelorThesis = "No title";
private int id;
public Student(String lname, String fname){
id = getRandomId();
firstName = fname;
lastName = lname;
}
public void setTitleOfBachelorThesis(String title){
try{
titleOfBachelorThesis = title;
}
catch(NullPointerException npe){
titleOfBachelorThesis = "No title";
}
}
public String toString(){
String student_data = "Student id: " + id + "\r\n" +
" FirstName: " + firstName + ", Lastname: " + lastName + "\r\n" +
" TitleOfBachelorsThesis: " + titleOfBachelorThesis;
return student_data;
}
private int getRandomId(){
Random random = new Random();
int id_nbr = random.nextInt(101);
return id_nbr;
}
}
The problem comes when I try to call the setTitleOfBachelorThesis method with null value like this:
import myclasses.Student;
public class mainclass{
public static void main(String[] args){
Student student = new Student("Mouse", "Mickey");
student.setTitleOfBachelorThesis(null);
System.out.println(student.toString());
}
}
And the error message is as follows:
Exception in thread "main" java.lang.NullPointerException
at myclasses.Student.setTitleOfBachelorThesis(Student.java:5)
at mainclass.main(mainclass.java:6)
I think this is weird since if I swap the null in the construction method call it works and the output is something like this:
Student id: 32
FirstName: Mickey, Lastname: null
TitleOfBachelorsThesis: Mouse
With this kind of mainclass:
import myclasses.Student;
public class mainclass{
public static void main(String[] args){
Student student = new Student(null, "Mickey");
student.setTitleOfBachelorThesis("Mouse");
System.out.println(student.toString());
}
}
I have tried to search how to handle the exceptions. I've tried using if (tile != null) and try{do x} catch(NullPointerException npe){do y} but it seems that the error happens on the method call and not inside of the method itself (if that makes sense). And I also find it weird how the constructor method can be called with the null value while the setTitleOfBachelorThesis can not.

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);
}

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.

Printing elements of list of objects [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 3 years ago.
//contacts class
package com.company;
public class Contacts {
private String name;
private String number;
public Contacts(String name, String number) {
this.name = name;
this.number = number;
}
public String getName() {
return name;
}
public String getNumber() {
return number;
}
}
//class Phone
package com.company;
import java.rmi.StubNotFoundException;
import java.util.ArrayList;
public class Phone {
private ArrayList<Contacts> contacts1 = new ArrayList<Contacts>();
public void addContact(String name, String numbers) {
Contacts contacts = new Contacts(name, numbers);
contacts1.add(contacts);
}
public void printContacts() {
for (int i = 0; i < contacts1.size(); i++) {
System.out.println(contacts1.); // >>> how to print elements (name and phone number)
}
}
}
Here I tried to print a list of contacts including name and phone number but could not handle how to iterate over a list of objects. How can I print name and phoneNumber using printContacts() method in Phone class?
Thanks
You would do:
System.out.println(contacts1.get(i));
but that would just give Contacts#somenumber, so you will need to add a toString() method to the Contacts class.
In the contacts class, add a function that looks like this:
#Override
public String toString() {
return name + ": " + number;
}
Override toString method in your class Contacts to return a string representation of your class object (for e.g. json string). System.out.println prints string returned by this method.
public class Contacts {
private String name;
private String number;
...
#Override
public String toString() {
return "{\"name\": \"" + name + "\", \"number\": \"" + number + "\"}";
}
}
P.S. If you are using one the java IDEs, check out the implementation of println method in file PrintStream.java in java source code. Java IDEs provides this feature of code navigation in your project by which you can actually navigate through source code of Java itself.

Final print statement returning null (java)

I have a basic name application that is taking in user data from the main class, splits the data in the parser class and then tries to assign everything in the final class and print it out in the toString method. I know the main class and the parser are working fine. I have verified in the parser class that the data DOES split properly and also sends the data through the object I made to the final class to assign it all. However, my final code is returning null..
MAIN CLASS
import java.util.Scanner;
public class MainClass {
public static void main (String[]args)
{
Scanner input = new Scanner(System.in); //create scanner object to gather name information
String fullName = null; //set the predefined value for the users name to null
nameParse splitInformation = new nameParse(); //method build to split the name into different sections
SecondClass access = new SecondClass(); //class built to output the different name data
System.out.println("What is your name?");
fullName = input.nextLine(); //store the users name and pass it into the data parser
splitInformation.parseNameInformation(fullName); //name parsing parameters built
System.out.println(access.toString());
}
}
Data Parser Class
public class nameParse {
private String firstName;
private String middleName;
private String lastName;
public nameParse()
{
firstName = "initial";
middleName = "initial";
lastName = "initial";
}
public void parseNameInformation(String inputInfo)
{
//Create an array to store the data and split it into multiple sectors
String nameInformation[] = inputInfo.split("\\s");
firstName = nameInformation[0];
middleName = nameInformation[1];
lastName = nameInformation[2];
//System.out.println(firstName + " " + middleName + " " + lastName);
SecondClass sendData = new SecondClass();
sendData.setFirstName(firstName);
sendData.setMiddleName(middleName);
sendData.setLastName(lastName);
}
}
Final Class
__
public class SecondClass {
private String firstName;
private String middleName;
private String lastName;
/*public String GFN()
{
return firstName;
}
public String GMN()
{
return middleName;
}
public String GLN()
{
return lastName;
}*/
public String setFirstName(String yourFirstName)
{
firstName = yourFirstName;
return this.firstName;
}
public String setMiddleName(String yourMiddleName)
{
middleName = yourMiddleName;
return this.middleName;
}
public String setLastName(String yourLastName)
{
lastName = yourLastName;
return this.lastName;
}
public String getFN()
{
return firstName;
}
public String toString()
{
String printNameInfo = "\nYour First Name:\t" + getFN();
return printNameInfo;
}
}
You never set any of your SecondClass object's (called "access") fields, so of course they'll all be null.
So in short, your code creates a nameParse object, gets information from the user, but does nothing with that information. You create a SecondClass object called access, put no data into it, and so should expect no valid data in it when you try to print it out. Solution: put information into your SecondClass object first. Call its setter methods:
// be sure to call the setter methods before trying to print anything out:
access.setSomething(something);
access.setSomethingElse(somethingElse);
Edit
You state:
I thought I set the data using the sendData.setFirstname(...) etc?
In the parseNameInformation method you create a new SecondClass object and you do set the fields of this object, but this object is completely distinct from the one in your main method whose fields are still null. To solve this, give parseNameInformation a method parameter and pass in your main method's SecondClass object into it and set its methods. You'll have to create the SecondClass object before calling the method of course.
i.e.,
public void parseNameInformation(String inputInfo, SecondClass sendData)
{
//Create an array to store the data and split it into multiple sectors
String nameInformation[] = inputInfo.split("\\s");
firstName = nameInformation[0];
middleName = nameInformation[1];
lastName = nameInformation[2];
//System.out.println(firstName + " " + middleName + " " + lastName);
// SecondClass sendData = new SecondClass(); // !!! get rid of this
sendData.setFirstName(firstName);
sendData.setMiddleName(middleName);
sendData.setLastName(lastName);
}

Java code making error [closed]

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 9 years ago.
Improve this question
I am trying to run the following java codes to make it look like this
But I am having problem I am not sure what I am doing wrong. I have three class testFacebook, Facebookperson, and facebook.
This is my code
public class testFacebook{
// This is the testFacebook class
public static void main (String[] argc){
System.out.println();
FacebookPerson p1 = new FacebookPerson("John");
System.out.println(p1.getName()+ "' mood is "+ p1.getMood() +".");
System.out.println(p1.getName()+ "' facebook content is "+ p1.getFacebookContent() +".");
p1.setMood("happy");
System.out.println(p1.getName()+ "' mood is "+ p1.getMood() +".");
System.out.println(p1.getName()+ "' facebook content is "+ p1.getFacebookContent() +".");
p1.setMood("sad");
System.out.println(p1.getName()+ "' mood is "+ p1.getMood() +".");
System.out.println(p1.getName()+ "' facebook content is "+ p1.getFacebookContent() +".");
}
}
public class FacebookPerson{
// This is the FacebookPerson class
private String myname;
private String mood;
private Facebook fb;
public FacebookPerson(String name){
myname = name;
mood ="initial mood";
fb = new Facebook();
}
public void setMood(String newMood){
mood = newMood;
fb.setContent(mood);
}
public String getMood(){
return mood;
}
public String getFacebookContent(){
return content;
}
public String getName(){
return name;
}
}
public class Facebook{
// This is the Facebook class
private String content;
public void setContent(String newContent){
content = newContent+"_content";
}
public Facebook(){
content = "initial_content";
}
}
But I am not sure what I am doing wrong...
Thats where the problem is :
public FacebookPerson(String name){
myname = name;
mood ="initial mood";
fb = new Facebook();
}
For initial mood, the constructor of Facebook sets the content to "null". It should be set to initial_content.
public Facebook(){
content = "null";
}
There are two issues.
Update the getFacebookContent() method in FacebookPerson to return the content using fb object as below.
public String getFacebookContent(){
return fb.getContent();
}
Implement getContent() method in Facebook as below:
public String getContent(){
return content;
}
In addition, you may want to initialize content variable as Initial_Content instead of null as you are expecting in the output.

Categories

Resources