Null Pointer Exception in creating an instance [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I have an exception and I don't know how to solve it.
Person a = new Person();
Scanner in = new Scanner(System.in);
System.out.println("Please type name: ");
String name = in.nextLine();
It says there's an exception in the first line.
The following code is the default constructor.
Person(){
this.name = "No_Name";
this.surname = "No_Surname";
this.number = "No_Number";
this.personalCode = "No_personalCode";
this.dateOfBirth.set(Calendar.DAY_OF_MONTH, 1);
this.dateOfBirth.set(Calendar.MONTH, Calendar.JANUARY);
this.dateOfBirth.set(Calendar.YEAR, 1900);
}
Class person full code:
import java.util.Calendar;
public class Person {
String name;
String surname;
private String number;
private String personalCode;
private Calendar dateOfBirth;
Person(){
this.name = "No_Name";
this.surname = "No_Surname";
this.number = "No_Number";
this.personalCode = "No_personalCode";
this.dateOfBirth.set(Calendar.DAY_OF_MONTH, 1);
this.dateOfBirth.set(Calendar.MONTH, Calendar.JANUARY);
this.dateOfBirth.set(Calendar.YEAR, 1900);
}
Person(String name,String surname,String number,String personalCode,Calendar dateOfBirth){
this.name = name;
this.surname = surname;
this.number = number;
this.personalCode = personalCode;
this.dateOfBirth = (Calendar) dateOfBirth.clone();
}
Person setName(Person a, String name) {
a.name = name;
return a;
}
Person setSurname(Person a, String surname) {
a.surname = surname;
return a;
}
Person setNumber(Person a, String number) {
a.number = number;
return a;
}
Person setpersonalCode(Person a, String personalCode) {
a.personalCode = personalCode;
return a;
}
String getName(Person a) {
return a.name;
}
String getSurname(Person a) {
return a.surname;
}
String getNumber(Person a) {
return a.number;
}
String getPersonalCode(Person a) {
return a.personalCode;
}
Calendar getDateOfBirth(Person a) {
return a.dateOfBirth;
}
}

You are calling set() on a null field (dateOfBirth).
A possibile workaround:
Date date = new GregorianCalendar(1900, Calendar.FEBRUARY, 1).getTime();
this.dateOfBirth = date;

Related

How to fix thid error ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1? [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 months ago.
I don't know where the problem is occurring I am trying to print customer details I already tried to change the variables but it didn't work What seems to be the problem? i already tried so many things but still not able to fix the errors.
import java.util.Scanner;
public class Main {
public static void main(String args[]) throws Exception {
Scanner sc = new Scanner(System.in);
String s1[] = sc.nextLine().split(" ");
String s2[] = sc.nextLine().split(" ");
String s3[] = sc.nextLine().split(" ");
int id = Integer.parseInt(s1[0]);
String name = s1[1];
String area = s2[0];
String city = s2[1];
int day = Integer.parseInt(s3[0]);
int month = Integer.parseInt(s3[1]);
int year = Integer.parseInt(s3[2]);
SimpleDate date = new SimpleDate(day, month, year);
Address add = new Address(area, city);
Customer c = new Customer(id, name, add, date);
System.out.print(c);
}
}
class SimpleDate {
private int day;
private int month;
private int year;
SimpleDate(int day, int month ,int year) {
this.day = day;
this.month = month;
this.year = year;
validateDate(this);
}
//gettens
public int getDay() {
return this.day;
}
public int getMonth() {
return this.month;
}
public int getYear() {
return this.year;
}
//setters
public void setDate(int day, int month, int year) {
this.day = day;
this.month = month;
this.year = year;
}
public static boolean validateDate(SimpleDate d) {
int day = d.getDay();
int month = d.getMonth();
int year = d.getYear();
if (year < 2000) {
return false;
}
if (month > 12 || month < 1) {
return false;
}
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
if (day < 1 || day >31)
return false;
break;
case 4:
case 6:
case 9:
case 11:
if (day < 1 || day > 30)
return false;
break;
case 2:
if (day < 1 | day > 28) {
return false;
}
break;
}
return true;
}
#Override
public String toString() {
return (day + "/" + month + "/" + year);
}
}
class Address {
private String area;
private String city;
Address(String area, String city) {
this.area = area;
this.city = city;
}
//getters
public String getArea() {
return area;
}
public String getCity() {
return city;
}
//setters
public void setArea(String area) {
this.area = area;
}
public void setCity(String city) {
this.area = city;
}
#Override
public String toString() {
return (area + ", " + city);
}
}
class Customer {
private int custID;
private String name;
private Address address;
private SimpleDate registrationDate;
Customer(int custID, String name, Address address, SimpleDate registrationDate) {
this.custID = custID;
this.name = name;
this.address = address;
if (!(SimpleDate.validateDate(registrationDate)))
this.registrationDate = null;
else
this.registrationDate = registrationDate;
}
//getters
public Address getAddress() {
return this.address;
}
public SimpleDate getRegistrationDate() {
return this.registrationDate;
}
//setters
public void setAddress(Address address) {
this.address = address;
}
public void setRegistrationDate(SimpleDate registrationDate) {
if (!(SimpleDate.validateDate(registrationDate))) {
this.registrationDate = null;
} else {
this.registrationDate = registrationDate;
}
}
#Override
public String toString() {
String date = "";
if (this.registrationDate == null)
date = "unkown";
else
date = this.registrationDate.toString();
String add = "";
if (this.address == null)
add = "Unkown";
else {
add = this.address.toString();
}
String s = String.format("Id: %d\n" +" Name: %s\n" + "Address : %s\n" + "Registere: %d\n");
return s;
}
}
Please give out more details.
What line causes this issue exactly?
Also you can remove all the code aside from the public static void since its never called
The two places that can be giving out the error are these two:
String name = s1[1];
String city = s2[1];
And the issue is the input you are giving them.
s1[1] and s2[1] points at the second word of the line on your input (arrays start at index 0).
So to solve your error your input would have to look like this:
name name
area
city city
And you are probably just writing the input the wrong way.
Or maybe you meant to write this:
String name = s1[0];
String city = s2[0];
There are many places explaining index out of bounds error before having to post a question on stackoverflow.
Please also check out the link in the comments below your question

How to send a date values to the constructor through object and how to get that date values back?

when I want to compile the below code compile-time error says: the
constructor Person(String, int ) is undefined, etc...
Person p = new Person("abhi",2/4/2019);
I wrote this code:
import java.util.Date;
class Person{
String name;
Date DOB;
public Person(String name, Date dOB) {
this.name = name;
DOB = dOB;
}
public String getName() {
return name;
}
public Date getDOB() {
return DOB;
}
}
class Student extends Person
{
int StudentID;
public Student(String name, Date dOB, int studentID) {
super(name, dOB);
StudentID = studentID;
}
public int getStudentID() {
return StudentID;
}
public static void main(String[] args) {
Person p = new Person("abhi",2/4/2019); // i can't pass date values to constructor
student s = new Student("mark",2019-04-01,123456); //i can't pass date values to constructor
System.out.println("Name "+p.getName());
System.out.println("DOB "+p.getDOB());
System.out.println("Name "+s.getName());
System.out.println("DOB "+s.getDOB());
System.out.println("StudID "+s.getStudentID());
}
}
`
In Java, 2/4/2019 is interpreted as an integer division (2 divided by 4 divided by 2019), i.e. 0. But it's definitely not a date.
Instead of using a Date object, I suggest using a LocalDate which is easier to use. Your code would then become:
Person p = new Person("abhi", LocalDate.of(2019, 4, 2));

how to sort a list of strings alphabetically in java?

Hie.
I am a Java beginner. I need to sort a String of names alphabetically.
i have a class that reads from a text file and writes the sorted file which filters by age(less than 18) but i need it to filter alphabetically, below is my implementation. Its working fine without filter by name.
public class PatientFileProcessor {
public void process(File source, File target) {
System.out.println("source"+source.getAbsolutePath());
System.out.println("target"+target.getAbsolutePath());
try {
writefile(target, filterbyAge(readfile(source)));
} catch (Exception ex) {
Logger.getLogger(PatientFileProcessor.class.getName()).log(Level.SEVERE, null, ex);
}
}
public List<Patient> readfile(File source) throws Exception {
List<Patient> patients = new ArrayList();
BufferedReader bf = new BufferedReader(new FileReader(source));
String s = bf.readLine();// ignore first line
while ((s = bf.readLine()) != null) {
String[] split = s.split("\\|");
System.out.println(Arrays.toString(split));
System.out.println(s+" "+split[0]+" "+split[1]+" "+split[2]);
Date d = new SimpleDateFormat("yyyy-dd-MM").parse(split[2]);
patients.add(new Patient(split[0], split[1], d));
}
return patients;
}
public void writefile(File target, List<Patient> sorted) throws Exception {
BufferedWriter pw = new BufferedWriter(new FileWriter(target));
DateFormat df = new SimpleDateFormat("yyyy/dd/MM");
for (Iterator<Patient> it = sorted.iterator(); it.hasNext();) {
Patient p = it.next();
pw.append(p.getName() + "|" + p.getGender() + "|" + df.format(p.getDob()));
pw.newLine();
}
pw.flush();
}
public List<Patient> filterbyAge(List<Patient> ps) {
List<Patient> sorted = new ArrayList();
for (Iterator<Patient> it = ps.iterator(); it.hasNext();) {
Patient s = it.next();
if (calcAge(s.getDob()) > 18) {
sorted.add(s);
}
}
return sorted;
}
public int calcAge(Date d) {
Date today = new Date();
long m = today.getTime() - d.getTime();
return (int) (m / (1000 * 60 * 60 * 24 * 365.25));
}
}
Patient:
import java.util.Date;
public class Patient {
private String name;
private String gender;
private Date dob;
public Patient() {
}
public Patient(String name, String gender, Date dob) {
this.name = name;
this.gender = gender;
this.dob = dob;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Date getDob() {
return dob;
}
}
how do i go about it?
Assuming that those are Strings, use the convenient static method sort…
java.util.Collections.sort(patients)
For Strings this would work:
arrayList.sort((p1, p2) -> p1.compareTo(p2)); (Java 8)
What you can do is you can implement the Comparable interface in your Patient and override the compareTo method. In that way, when the sort method of Collections is called, it will use the your compareTo method for comparison.

Display multiple String items Java

I have a last Java homework task, this task is about employees,
my method should print employee's names and surnames, worked more than "n" years.
What I've done for now:
public class LastTask {
public static void main(String[] args) {
Employee employee1 = new Employee("Dobrobaba", "Irina", "Ivanovna",
"Moskva", 1900, 6);
Employee employee2 = new Employee("Shmal", "Anna", "Nikolaevna",
"Krasnodar", 2017, 8);
Employee employee3 = new Employee("Kerimova", "Niseimhalum", "Magomedmirzaevna",
"New-York", 2010, 3);
Employee employee4 = new Employee("Dobryden", "Yuri", "Viktorovich",
"Auckland", 2000, 11);
Employee employee5 = new Employee("Lopata", "Leonid", "Nikolaevich",
"Beijing", 2014, 11);
}
/**
* Prints employees' information, which have worked more than 'n' year(s) for now.
*
* #param n years quantity
* #return the String, contained surname, name, patronymic and address of the specific employee(s).
*/
public static String displayEmployees(int n) {
return null;
}
}
class Employee {
private String surname;
private String name;
private String patronymic;
private String address;
private int employmentYear;
private int employmentMonth;
Employee(String surname, String name, String patronymic, String address, int employmentYear, int employmentMonth) {
this.surname = surname;
this.name = name;
this.patronymic = patronymic;
this.address = address;
this.employmentYear = employmentYear;
this.employmentMonth = employmentMonth;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPatronymic() {
return patronymic;
}
public void setPatronymic(String patronymic) {
this.patronymic = patronymic;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getEmploymentYear() {
return employmentYear;
}
public void setEmploymentYear(int employmentYear) {
this.employmentYear = employmentYear;
}
public int getEmploymentMonth() {
return employmentMonth;
}
public void setEmploymentMonth(int employmentMonth) {
this.employmentMonth = employmentMonth;
}
}
I made a parametrised constructor for creating employees with multiple parameters, also made parameters encapsulated.
Have no clue what to do next, task says that I can use List/ArrayList, but after some time googling about it, I still can't understand how to implement a condition like if (employmentYear - currentYear >= n) then return employee1, employee4 for example.
Could you give me some tips?
Thank you for your attention.
You can create a static ArrayList and add those all employees to that ArrayList, and in displayEmployees method you can stream that list based on condition if employee EmploymentYear greater than n print details and add to another list so finally if you want you can just return count of employees or you can return List of employees also
public class LastTask {
static List<Employee> employee = new ArrayList<>();
public static void main(String[] args) {
Employee employee1 = new Employee("Dobrobaba", "Irina", "Ivanovna",
"Moskva", 1900, 6);
Employee employee2 = new Employee("Shmal", "Anna", "Nikolaevna",
"Krasnodar", 2017, 8);
Employee employee3 = new Employee("Kerimova", "Niseimhalum", "Magomedmirzaevna",
"New-York", 2010, 3);
Employee employee4 = new Employee("Dobryden", "Yuri", "Viktorovich",
"Auckland", 2000, 11);
Employee employee5 = new Employee("Lopata", "Leonid", "Nikolaevich",
"Beijing", 2014, 11);
employee.add(employee1);
employee.add(employee2);
employee.add(employee3);
employee.add(employee4);
employee.add(employee5);
}
/**
* Prints employees' information, which have worked more than 'n' year(s) for now.
*
* #param n years quantity
* #return the String, contained surname, name, patronymic and address of the specific employee(s).
*/
public static int displayEmployees(int n) {
List<Employee> finalList = new ArrayList<>();
employee.stream().forEach(emp->{
if(emp.getEmploymentYear()-Year.now().getValue()>=n) {
System.out.println("Employee Name : "+emp.getName()+" Sur Aame : "+emp.getSurname());
finalList.add(emp);
}
});
return finalList.size();
}
}
If you are looking for a way to find "worked more than 'n' years", this might help you.
Calendar.getInstance().get(Calendar.YEAR) - employmentYear >= n
Add a proper toString() method in the Employee class to get the desired output, apart from that I have used the filter() method from the Stream object to filter through the Employee objects. I am passing the number of years worked as an input parameter and calculating the years served in employment from the employmentYear field.
package com.company;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.stream.Collectors;
public class LastTask {
private static List<Employee> listEmps;
public static void main(String[] args) {
Employee employee1 = new Employee("Dobrobaba", "Irina", "Ivanovna",
"Moskva", 1900, 6);
Employee employee2 = new Employee("Shmal", "Anna", "Nikolaevna",
"Krasnodar", 2017, 8);
Employee employee3 = new Employee("Kerimova", "Niseimhalum", "Magomedmirzaevna",
"New-York", 2010, 3);
Employee employee4 = new Employee("Dobryden", "Yuri", "Viktorovich",
"Auckland", 2000, 11);
Employee employee5 = new Employee("Lopata", "Leonid", "Nikolaevich",
"Beijing", 2014, 11);
listEmps = new ArrayList<>(Arrays.asList(employee1,employee2,employee3,employee4,employee5));
//display employee details of employees who worked more than 17 years.
displayEmployees(17);
}
/**
* Prints employees' information, which have worked more than 'n' year(s) for now.
*
* #param n years quantity
* #return the String, contained surname, name, patronymic and address of the specific employee(s).
*/
public static void displayEmployees(int n) {
int year = Calendar.getInstance().get(Calendar.YEAR);
listEmps.stream()
.filter(emp ->{
return year - emp.getEmploymentYear() > n;
})
.collect(Collectors.toList())
.forEach(System.out::println);
}
}
class Employee {
private String surname;
private String name;
private String patronymic;
private String address;
private int employmentYear;
private int employmentMonth;
Employee(String surname, String name, String patronymic, String address, int employmentYear, int employmentMonth) {
this.surname = surname;
this.name = name;
this.patronymic = patronymic;
this.address = address;
this.employmentYear = employmentYear;
this.employmentMonth = employmentMonth;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPatronymic() {
return patronymic;
}
public void setPatronymic(String patronymic) {
this.patronymic = patronymic;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getEmploymentYear() {
return employmentYear;
}
public void setEmploymentYear(int employmentYear) {
this.employmentYear = employmentYear;
}
public int getEmploymentMonth() {
return employmentMonth;
}
public void setEmploymentMonth(int employmentMonth) {
this.employmentMonth = employmentMonth;
}
#Override
public String toString(){
return "Employee details: " + this.name + this.surname + this.address + this.employmentYear;
}
}

How to convert multiple string into arraylist?

I m new in android.I want to add these String variables to ArrayList, what I am doing now.
Suppose I have a four of String Variables.....
String number = "9876543211";
String type = "incoming";
String date = "1/1/2016";
String duration = "45 sec";
Here is my java code.......
while (managedCursor.moveToNext()) {
String number = managedCursor.getString(number1);
String type2 = managedCursor.getString(type1);
String date = managedCursor.getString(managedCursor.getColumnIndexOrThrow("date")).toString();
java.util.Date date1 = new java.util.Date(Long.valueOf(date));
String duration = managedCursor.getString(duration1);
String type = null;
String fDate = date1.toString();
int callcode = Integer.parseInt(type2);
sb.append("\nPhone Number:--- " + number + "");
sb.append(" \nCall Type:--- " + type + " ");
sb.append("\nCall Date:--- " + fDate + "");
sb.append("\nCall duration in sec :--- " + duration);
sb.append("\n----------------------------------");
}
As 4castle suggest, you should really have a custom class - which looking at the properties you are interested in, you might want to name "CallLogEntry" and then have properties for this class. Here is an example of such a custom class.
public class CallLogEntry {
String number;
String type;
String date;
String duration; //this should ideally be of type Long (milliseconds)
public CallLogEntry(){
//do stuff if necessary for no-params constructor
}
public CallLogEntry(String number, String type, String date, String duration){
this.number = number;
this.type = type;
this.date = date;
this.duration = duration;
}
//getters and setters go here..
getNumber(){ return this.number;}
setNumber(String number){ this.number = number;}
//...the rest of them...
}
Than it makes more sense to have an ArrayList of CallHistoryEntry items like this:
//...declare list of call-log-entries:
List<CallLogEntry> callLogEntryList = new ArrayList<CallLogEntry>();
//...add entries
CallLogEntry entry = new CallLogEntry(number, type, date, duration);
callLogEntryList.add(entry);
The advantage of doing it like this, especially in an Android app, is that later you may pass this list to some list-adapter for a list-view.
I hope this helps.
Create JavaBean Class as follows
public class DataBean {
String number;
String type;
String date;
String duration;
public DataBean(String number, String type, String date, String duration) {
this.number = number;
this.type = type;
this.date = date;
this.duration = duration;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
}
Now create Arryalist as follows
ArrayList<DataBean> dataBeanList = new ArrayList<>();
DataBean dataBean=new DataBean(number,type,date,duration);
dataBeanList.add(dataBean);//added bean object arrylist
For Retrieving data do as follow
// iterate through arraylist as follows
for(DataBeand d: dataBeanList ){
if(d.getName() != null && d.getDate()!=null)
//something here
}

Categories