Java code making error [closed] - java

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.

Related

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]

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.

Parsing multiple JSON objects that exist in one line in Java

I'm currently using the OMDB API, which can either return get-queries as JSON objects or XML. Working with JSON is something I'd like to learn, and it generally seems like best solution for what I'm trying to do. The implementation I'm hoping for, is to allow the user to search for a movie, and select the correct one from a list. I'm currently using the google.gson library.
The problem I've run in to, is that the searching for movies by a title with OMDB, this example being "batman", returns the following String:
{"Search":[{"Title":"Batman Begins","Year":"2005","imdbID":"tt0372784","Type":"movie","Poster":"https://m.media-amazon.com/images/M/MV5BOTY4YjI2N2MtYmFlMC00ZjcyLTg3YjEtMDQyM2ZjYzQ5YWFkXkEyXkFqcGdeQXVyMTQxNzMzNDI#._V1_SX300.jpg"},{"Title":"Batman v Superman: Dawn of Justice","Year":"2016","imdbID":"tt2975590","Type":"movie","Poster":"https://m.media-amazon.com/images/M/MV5BYThjYzcyYzItNTVjNy00NDk0LTgwMWQtYjMwNmNlNWJhMzMyXkEyXkFqcGdeQXVyMTQxNzMzNDI#._V1_SX300.jpg"},{"Title":"Batman","Year":"1989","imdbID":"tt0096895","Type":"movie","Poster":"https://m.media-amazon.com/images/M/MV5BMTYwNjAyODIyMF5BMl5BanBnXkFtZTYwNDMwMDk2._V1_SX300.jpg"},{"Title":"Batman Returns","Year":"1992","imdbID":"tt0103776","Type":"movie","Poster":"https://m.media-amazon.com/images/M/MV5BOGZmYzVkMmItM2NiOS00MDI3LWI4ZWQtMTg0YWZkODRkMmViXkEyXkFqcGdeQXVyODY0NzcxNw##._V1_SX300.jpg"},{"Title":"Batman Forever","Year":"1995","imdbID":"tt0112462","Type":"movie","Poster":"https://m.media-amazon.com/images/M/MV5BNDdjYmFiYWEtYzBhZS00YTZkLWFlODgtY2I5MDE0NzZmMDljXkEyXkFqcGdeQXVyMTMxODk2OTU#._V1_SX300.jpg"},{"Title":"Batman & Robin","Year":"1997","imdbID":"tt0118688","Type":"movie","Poster":"https://m.media-amazon.com/images/M/MV5BMGQ5YTM1NmMtYmIxYy00N2VmLWJhZTYtN2EwYTY3MWFhOTczXkEyXkFqcGdeQXVyNTA2NTI0MTY#._V1_SX300.jpg"},{"Title":"The Lego Batman Movie","Year":"2017","imdbID":"tt4116284","Type":"movie","Poster":"https://m.media-amazon.com/images/M/MV5BMTcyNTEyOTY0M15BMl5BanBnXkFtZTgwOTAyNzU3MDI#._V1_SX300.jpg"},{"Title":"Batman: The Animated Series","Year":"1992–1995","imdbID":"tt0103359","Type":"series","Poster":"https://m.media-amazon.com/images/M/MV5BOTM3MTRkZjQtYjBkMy00YWE1LTkxOTQtNDQyNGY0YjYzNzAzXkEyXkFqcGdeQXVyOTgwMzk1MTA#._V1_SX300.jpg"},{"Title":"Batman: Under the Red Hood","Year":"2010","imdbID":"tt1569923","Type":"movie","Poster":"https://m.media-amazon.com/images/M/MV5BNmY4ZDZjY2UtOWFiYy00MjhjLThmMjctOTQ2NjYxZGRjYmNlL2ltYWdlL2ltYWdlXkEyXkFqcGdeQXVyNTAyODkwOQ##._V1_SX300.jpg"},{"Title":"Batman: The Dark Knight Returns, Part 1","Year":"2012","imdbID":"tt2313197","Type":"movie","Poster":"https://m.media-amazon.com/images/M/MV5BMzIxMDkxNDM2M15BMl5BanBnXkFtZTcwMDA5ODY1OQ##._V1_SX300.jpg"}],"totalResults":"490","Response":"True"}
Thus far, I've managed to remove the {"Search":[ and ],"totalResults":"490","Response":"True"} part using sendGetRequest(requestURL).substring(11, sendGetRequest(requestURL).length()-41);, yet I still can't seem to parse the String as JSON. I've tried using String.split and Matcher/Pattern with various regexes, to separate the the JsonObjects. I've also tried a JSONArray, but to no avail.
I'm new to working with JSON, so it's not unlikely I'm missing something obvious or have completely misunderstood JSON in general.
First define a new custom class for your need:
import com.fasterxml.jackson.annotation.JsonProperty;
public class YourClass {
#JsonProperty("Title")
private String title;
#JsonProperty("Year")
private String year;
private String imdbID;
#JsonProperty("Type")
private String type;
#JsonProperty("Poster")
private String poster;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getImdbID() {
return imdbID;
}
public void setImdbID(String imdbID) {
this.imdbID = imdbID;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getPoster() {
return poster;
}
public void setPoster(String poster) {
this.poster = poster;
}
#Override
public String toString() {
return "YourClass{" +
"title='" + title + '\'' +
", year='" + year + '\'' +
", imdbID='" + imdbID + '\'' +
", type='" + type + '\'' +
", poster='" + poster + '\'' +
'}';
}
}
Then simply you can parse your JSON, this is main method:
public static void main(String[] args) throws JsonProcessingException {
SpringApplication.run(Demo2Application.class, args);
ObjectMapper objectMapper = new ObjectMapper();
List<YourClass> yourClassList = objectMapper.readValue("[{\"Title\":\"Batman Begins\",\"Year\":\"2005\",\"imdbID\":\"tt0372784\",\"Type\":\"movie\",\"Poster\":\"https://m.media-amazon.com/images/M/MV5BOTY4YjI2N2MtYmFlMC00ZjcyLTg3YjEtMDQyM2ZjYzQ5YWFkXkEyXkFqcGdeQXVyMTQxNzMzNDI#._V1_SX300.jpg\"},{\"Title\":\"Batman v Superman: Dawn of Justice\",\"Year\":\"2016\",\"imdbID\":\"tt2975590\",\"Type\":\"movie\",\"Poster\":\"https://m.media-amazon.com/images/M/MV5BYThjYzcyYzItNTVjNy00NDk0LTgwMWQtYjMwNmNlNWJhMzMyXkEyXkFqcGdeQXVyMTQxNzMzNDI#._V1_SX300.jpg\"},{\"Title\":\"Batman\",\"Year\":\"1989\",\"imdbID\":\"tt0096895\",\"Type\":\"movie\",\"Poster\":\"https://m.media-amazon.com/images/M/MV5BMTYwNjAyODIyMF5BMl5BanBnXkFtZTYwNDMwMDk2._V1_SX300.jpg\"},{\"Title\":\"Batman Returns\",\"Year\":\"1992\",\"imdbID\":\"tt0103776\",\"Type\":\"movie\",\"Poster\":\"https://m.media-amazon.com/images/M/MV5BOGZmYzVkMmItM2NiOS00MDI3LWI4ZWQtMTg0YWZkODRkMmViXkEyXkFqcGdeQXVyODY0NzcxNw##._V1_SX300.jpg\"},{\"Title\":\"Batman Forever\",\"Year\":\"1995\",\"imdbID\":\"tt0112462\",\"Type\":\"movie\",\"Poster\":\"https://m.media-amazon.com/images/M/MV5BNDdjYmFiYWEtYzBhZS00YTZkLWFlODgtY2I5MDE0NzZmMDljXkEyXkFqcGdeQXVyMTMxODk2OTU#._V1_SX300.jpg\"},{\"Title\":\"Batman & Robin\",\"Year\":\"1997\",\"imdbID\":\"tt0118688\",\"Type\":\"movie\",\"Poster\":\"https://m.media-amazon.com/images/M/MV5BMGQ5YTM1NmMtYmIxYy00N2VmLWJhZTYtN2EwYTY3MWFhOTczXkEyXkFqcGdeQXVyNTA2NTI0MTY#._V1_SX300.jpg\"},{\"Title\":\"The Lego Batman Movie\",\"Year\":\"2017\",\"imdbID\":\"tt4116284\",\"Type\":\"movie\",\"Poster\":\"https://m.media-amazon.com/images/M/MV5BMTcyNTEyOTY0M15BMl5BanBnXkFtZTgwOTAyNzU3MDI#._V1_SX300.jpg\"},{\"Title\":\"Batman: The Animated Series\",\"Year\":\"1992–1995\",\"imdbID\":\"tt0103359\",\"Type\":\"series\",\"Poster\":\"https://m.media-amazon.com/images/M/MV5BOTM3MTRkZjQtYjBkMy00YWE1LTkxOTQtNDQyNGY0YjYzNzAzXkEyXkFqcGdeQXVyOTgwMzk1MTA#._V1_SX300.jpg\"},{\"Title\":\"Batman: Under the Red Hood\",\"Year\":\"2010\",\"imdbID\":\"tt1569923\",\"Type\":\"movie\",\"Poster\":\"https://m.media-amazon.com/images/M/MV5BNmY4ZDZjY2UtOWFiYy00MjhjLThmMjctOTQ2NjYxZGRjYmNlL2ltYWdlL2ltYWdlXkEyXkFqcGdeQXVyNTAyODkwOQ##._V1_SX300.jpg\"},{\"Title\":\"Batman: The Dark Knight Returns, Part 1\",\"Year\":\"2012\",\"imdbID\":\"tt2313197\",\"Type\":\"movie\",\"Poster\":\"https://m.media-amazon.com/images/M/MV5BMzIxMDkxNDM2M15BMl5BanBnXkFtZTcwMDA5ODY1OQ##._V1_SX300.jpg\"}]", new TypeReference<ArrayList<YourClass>>() {});
for (YourClass yourClass: yourClassList) {
System.out.println(yourClass);
}
}
P.S: Keep in your mind that you must not remove brackets [] from your JSON as you said in your question.

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.

How to return a private variable

Ok so I'm trying to get a better understanding of how to return a private variable from a class that I have created. I've only provided a small snippet of my main program to explain my question, so if more information is needed please let me know. My goal is to return a string from the class (working great), but also be able to return the private variables individually as needed (example used below is "flight_number").
public class Flights {
private String dest_city, dest_state, departureDate, departureTime;
private int flight_number;
public Flights(String city, String state, String dDate, String dTime, int flightNumber) {
dest_city = city;
dest_state = state;
departureDate = dDate;
departureTime = dTime;
flight_number = flightNumber;
}
public String toString() {
return "Flight number: " + flight_number + " Destination: " + dest_city + "," + dest_state + " Departing on:" + departureDate + " at" + departureTime + ".";
}
}
public class dummy {
public static void main(String[] args) {
// Uses the constructor to set values
Flights flight1 = new Flights("Houston", "Texas", "12/20/2014", "12:40 pm", 100);
System.out.println(flight1);
System.out.println(flight_number); // Error: `flight_number` cannot be resolved to a variable.
}
}
You need to add a public getter in Flights and call it from main:
public class Flights {
// all the private fields
public int getFlightNumber() {
return this.flight_number;
}
}
In Main:
public static void main(String[] args) {
Flights flight1 = new Flights("Houston", "Texas"); //...
System.out.println(flight1);
System.out.println(flight1.getFlightNumber()); // call the getter
}
You should start with an editor like eclipse and that should help you get started quickly. Getters and Setters is what you need, but start with Eclipse and you should do better.

How to manipulate value from a return string in Java [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 have a variable that contains a return value.
Value:
Team ID:
111111
Founded:
Feb 13, 2014 By USER
Dispute Percentage:" 0%
Reputation: -
What I am looking to keep is stickly (11111) and save it back to the value teamID. How can I manipulate the return string to only store that value and delete the rest.
If I understand what you want, you can do something like this
String value = "Team ID:\n" + "19288568\n"
+ "Founded:\n" + "Feb 13, 2014 By MLGQA\n"
+ "\n" + "Dispute Percentage: 0%\n"
+ "Reputation: -\n";
System.out.println(value.split("\n")[1]);
Outputs
19288568
Since your returned String seems somewhat complex to me, I would suggest returning a custom object (a bean) containing the information you want, each with its own field.
By doing that, you will have a quick access to any of the fields you want, by simply calling the appropriate getter method on the returned object.
For example:
public class MyContainer {
private int teamID;
private String foundationDate;
private String foundator;
private int disputePercentage;
private int reputation;
public MyContainer() {
// Constructor code.
}
public int getTeamID() {
return teamID;
}
public void setTeamID(int teamID) {
this.teamID = teamID;
}
public String getFoundationDate() {
return foundationDate;
}
public void setFoundationDate(String foundationDate) {
this.foundationDate = foundationDate;
}
public String getFoundator() {
return foundator;
}
public void setFoundator(String foundator) {
this.foundator = foundator;
}
public int getDisputePercentage() {
return disputePercentage;
}
public void setDisputePercentage(int disputePercentage) {
this.disputePercentage = disputePercentage;
}
public int getReputation() {
return reputation;
}
public void setReputation(int reputation) {
this.reputation = reputation;
}
}
And your original returning method would look to something like this:
public MyContainer returningMethod(Object args) {
// Your code.
MyContainer bean = new MyContainer();
// Fill the container.
return bean;
}
I do not know the exact types of data you use, so feel free to adjust this example for your needs!

Categories

Resources