My code compiles well, except when displaying the inputted info, i am getting an error i dont understand:
**Exception in thread "main" java.lang.NullPointerException
at Employee.(Employee.java:18)
at unit11.main(unit11.java:50)**
My Code is attached below.
public class Employee {
public Name name;
public Date date;
public Address address;
public String[] data;
public Employee(String first, String last,
int inMont, int inDay, int inYear,
String inStreet, String inCity, String inState, String inZip){
if (errorCheck(inMont, inDay, inYear, inState, inZip) == 1)
System.out.println("Error in data. Please try again.");
else{
name = new Name(first, last);
date = new Date(inMont, inDay, inYear);
address = new Address(inStreet, inCity, inState, inZip);
data[0] = name.firstName + " " + name.lastName;
data[1] = date.month + " " + date.day + ", " + date.year;
data[2] = address.street + ", " + address.city + ", " + address.state + ", " + address.zip;
}
}
public int errorCheck(int inMonth, int inDay, int inYear,String inState, String inZip){
if(inMonth < 1 || inMonth > 12 || inYear < 1000 ||
inDay < 1 || inDay > 31 ||
((inMonth == 4 || inMonth == 6 || inMonth == 9 || inMonth == 11) && inDay > 30)
|| (inMonth == 2 && inDay > 29) || inState.length() != 2)
return 1;
else return 0;
}
}
//and line 50 in the unit11 code( is the employees[i] part)
if(errorCheck(month, day, year, state, zip) ==1)
System.out.println("Invalid data input. Please try again.");
else{
employees[i] = new Employee(firstName, lastName, month, day, year, street, city, state, zip);
i++;
}
Your constructor is expecting inZip to be an int:
public Employee(String first, String last,
int inMont, int inDay, int inYear,
String inStreet, String inCity, String inState, int inZip)
But it's a String:
String zip = input.nextLine();
Postal codes aren't integers, they're strings. Change the constructor/class/etc. to expect a string.
Related
So for this assignment, it asks the user to enter a phone number, then it splits the number up into a category of each set of integers. What I'm attempting to do is to throw a simple exception that if they do not enter the parenthesis for the area code that it throws the exception but doesn't crash the program and asks them to re-enter using the correct format
public class App{
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);
String inputNum;
String token1[];
String token2[];
String areaCode;
String preFix;
String lineNum;
String fullNum;
System.out.print("Enter a phone number in (123) 123-4567 format: ");
inputNum = input.nextLine();
System.out.println();
token1 = inputNum.split(" ");
areaCode = token1[0].substring(1, 4);
if (token1[0].substring(0, 3) != "()"){
throw new Exception("Enter a phone number in (123) 123-4567 format: ");
}
token2 = token1[1].split("-");
preFix = token2[0];
lineNum = token2[1];
fullNum = "(" + areaCode + ")" + " " + preFix + "-" + lineNum ;
System.out.print("Area code: " + areaCode + "\n");
System.out.print("Prefix: " + preFix + "\n");
System.out.print("Line number: " + lineNum + "\n");
System.out.print("Full number: " + fullNum);
}
}
No need to throw. Just keep asking in a loop.
String areaCode;
String preFix;
String lineNum;
while (true) {
System.out.print("Enter a phone number in (123) 123-4567 format: ");
String inputNum = input.nextLine();
System.out.println();
String [] token1 = inputNum.split(" ");
if (token1.length == 2 && token1[0].length() == 5
&& token1[0].charAt(0) == '(' && token1[0].charAt(4) == ')') {
areaCode = token1[0].substring(1, 4);
String [] token2 = token1[1].split("-");
if (token2.length == 2 && token2[0].length() == 3 && token2[1].length() == 4) {
preFix = token2[0];
lineNum = token2[1];
// If we reach this line all is ok. Exit the loop.
break;
}
}
}
String fullNum = "(" + areaCode + ")" + " " + preFix + "-" + lineNum ;
System.out.print("Area code: " + areaCode + "\n");
System.out.print("Prefix: " + preFix + "\n");
System.out.print("Line number: " + lineNum + "\n");
System.out.print("Full number: " + fullNum);
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
I have this code, and I keep getting an array index out of bounds error. I really do not know why. Can anyone please explain me why?
String[] splitter= entry.split(" ");
String name = "";
String burialDate = "";
String age = "";
for(int i = 0; i < entry.length(); i++)
{
if(splitter[i].equals(""))
{
if((splitter[i].charAt(0) <= '9' && splitter[i].charAt(0) >= '0'))
{
int index = i;
break;
}
else
name = name + splitter[i] + " ";
}
}
name = name.substring(0, name.length()-1);
burialDate = splitter[index] + " " + splitter[index+1] + " " + splitter[index+2];
age = splitter[index+1];
Person person = new Person(name, burialDate, age);
return person;
Your int index was defined inside the for loop, inside a nested if statement. Quite frankly, the scope of the int is extremely limited.
You should be defining the int index outside of the for loop like so:
String[] splitter= entry.split(" ");
String name = "";
String burialDate = "";
String age = "";
int index = 0;
for(int i = 0; i < entry.length(); i++)
{
if(splitter[i].equals(""))
{
if((splitter[i].charAt(0) <= '9' && splitter[i].charAt(0) >= '0'))
{
index = i;
break;
}
else
name = name + splitter[i] + " ";
}
}
name = name.substring(0, name.length()-1);
burialDate = splitter[index] + " " + splitter[index+1] + " " + splitter[index+2];
age = splitter[index+1];
Person person = new Person(name, burialDate, age);
return person;
When I input "today" in the code below, if(date_holder.contains("/")) executes. How do I fix this?
Sorry for the sloppiness of my code. Any help is appreciated.
import java.util.*;
import java.io.*;
import java.text.*;
/**
* Write a description of class Driver here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class Driver
{
//extra credit
//do you want to enter a date or use todays date can use api to get it
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int day = 0;
int month = 0;
int year = 0;
char choice;
String date_holder;
StringTokenizer stok;
int count = 0; // use this variable to create all of the sub menus
//for example 0 is the first sub menu 1 s the next sub menu
while(count == 0)
{
System.out.println("Enter a date or type 'today' for todays date \nor enter 'quit' to quit: ");
date_holder = keyboard.next();
date_holder.trim();//trim any white space
System.out.println("!## " + date_holder);
if(date_holder.contains("/"))
{
stok = new StringTokenizer(date_holder,"/");
month = Integer.parseInt(stok.nextToken());
day = Integer.parseInt(stok.nextToken());
year = Integer.parseInt(stok.nextToken());
Date date = new Date(day, month, year);
count = 1;
while(count == 1)
{
do
{
//zz
System.out.println("Current Date: " + month + "/" + day + "/" + year +
"\nEnter 'a' if you want to add days to the date \n" +
"or enter a 's' if you want to subtract the date \n" +
"or enter a 'd' get the days between the current date and another date \n " +
"or enter a 'f' if you want to format the date.\n");
choice = keyboard.next().charAt(0);
}while(choice != 'a' && choice != 's' && choice != 'd' && choice != 'f');
String number; //to store the user's number input
String answer;
if(choice == 'a')//too add the date
{
System.out.println("Enter a number to add:");
number = keyboard.next();
date.add(Integer.parseInt(number));
answer = date.toString();
System.out.println("answer: " + answer);
count = 0;
}
else if(choice == 's')//too subtract the date
{
System.out.println("Enter a number of days to subtract:");
number = keyboard.next();
date.subtract(Integer.parseInt(number));
answer = date.toString();
System.out.println("answer: " + answer);
count = 0;
}
else if(choice == 'd')//too get the days between
{
int inMonth, inDay, inYear = 0;
System.out.println("Enter a date to use with " + month + "/" + day +
"/" + year + ":");
number = keyboard.next();
if(number.contains("/"))
{
stok = new StringTokenizer(number,"/");
inMonth = Integer.parseInt(stok.nextToken());
inDay = Integer.parseInt(stok.nextToken());
inYear = Integer.parseInt(stok.nextToken());
Date inDate = new Date(inDay, inMonth, inYear);
Date outDate = new Date(day, month, year);
if(year < inYear)
{
System.out.println("The days between " + date.toString() +
"and" + inDate.toString() + " is " + inDate.daysBetween(outDate) + " days.");
}
else
{
System.out.println("The days between " + date.toString() +
"and" + inDate.toString() + " is " + outDate.daysBetween(inDate) + "days.");
}
count = 0;
}
}
else if(choice == 'f')//too change the format and (extra credit)
{
do
{
//zz
System.out.println("Current Date: " + month + "/" + day + "/" + year +
"\nEnter 's' if you want the format day//month//year \n" +
"or enter a 'l' if you want the format day of month, year \n" +
"or enter a 'j' to get the Julian date \n" +
"or enter a 'h' if you want to get the horoscope Zodiac of the date.\n" +
"or enter a 'c' if you want to get the Chinese Zodiac of the date.\n"+
"or enter a 'e' if you want to get the Easter date of the year.\n");
choice = keyboard.next().charAt(0);
}while(choice != 's' && choice != 'l' && choice != 'j' && choice != 'h' && choice != 'c' && choice != 'e');
//I don't need any if statments to verify the choices because
//it is all handled in the getDate() method
System.out.println(date.getDate(choice));
count = 0;//end the submenu loop
}
}
}
else if(date_holder.equals("today"))
{
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal));
}
else if(date_holder.equals("quit"))
{
count = -1;
}
}
System.out.println("goodbye!");
}
}
Your Code works fine when I give today it prints the today's date with the format you mentioned but change your code to below.
else if(date_holder.equals("today"))
{
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));
}
You cannot format the calendar object you have to use getTime method to get the Date object.
Your code looks quite clumsy please study more about the Date api here
In the following code, I'm having problems getting each part of the program to run the respective methods. Individually testing them, they work fine. However, I don't think the fileIn.next() is working how I need it to to get the letters and numbers to appear in order for the right statement to run. Often, I'll get a NoSuchElementException and I cannot figure out what steps I need to take to fix it.
Edit 1: Sorry if the formatting is getting wonky, but I added the class I had to create with the methods I mentioned. I also noticed after one iteration, the letters in my file stop appearing somehow?
import java.util.*;
import java.io.*;
public class p2{
public static void main(String[] args) throws IOException{
Date date1 = new Date();
Date date2 = new Date();
Date date3 = new Date(5, 31, 2016);
System.out.println();
Scanner fileIn = new Scanner(new File("test1.txt"));
while (fileIn.next() != null ){
if (fileIn.next().equals("G") && fileIn.next().equals("1")){
date1.getDate();
}
if (fileIn.next().equals("G") && fileIn.next().equals("2")){
date2.getDate();
}
if (fileIn.next().equals("G") && fileIn.next().equals("3")){
date3.getDate();
}
if (fileIn.next().equals("I") && fileIn.nextInt() == 1){
date1.incrementDay();
}
if (fileIn.next().equals("I") && fileIn.nextInt() == 2){
date2.incrementDay();
}
if (fileIn.next().equals("I") && fileIn.nextInt() == 3){
date3.incrementDay();
}
if (fileIn.next().equals("D") && fileIn.nextInt() == 1){
date1.displayDate();
}
if (fileIn.next().equals("D") && fileIn.nextInt() == 2){
date2.displayDate();
}
if (fileIn.next().equals("D") && fileIn.nextInt() == 3){
date3.displayDate();
}
if (fileIn.next().equals("S") && fileIn.nextInt() == 1){
String newDate = fileIn.next();
//System.out.println("newDate: " + newDate);
int num1 = Integer.parseInt(newDate.substring(0, 2));
int num2 = Integer.parseInt(newDate.substring(3, 5));
int num3 = Integer.parseInt(newDate.substring(6, 10));
System.out.println(num1 + "/" + num2 + "/" + num3);
date1.setDate(num1, num2, num3);
}
if (fileIn.next().equals("S") && fileIn.nextInt() == 2){
String newDate = fileIn.next();
//System.out.println("newDate: " + newDate);
int num1 = Integer.parseInt(newDate.substring(0, 2));
int num2 = Integer.parseInt(newDate.substring(3, 5));
int num3 = Integer.parseInt(newDate.substring(6, 10));
System.out.println(num1 + "/" + num2 + "/" + num3);
date2.setDate(num1, num2, num3);
}
if (fileIn.next().equals("S") && fileIn.nextInt() == 3){
String newDate = fileIn.next();
//System.out.println("newDate: " + newDate);
int num1 = Integer.parseInt(newDate.substring(0, 2));
int num2 = Integer.parseInt(newDate.substring(3, 5));
int num3 = Integer.parseInt(newDate.substring(6, 10));
System.out.println(num1 + "/" + num2 + "/" + num3);
date3.setDate(num1, num2, num3);
}
if (fileIn.next().equals("Q")){
System.exit(0);
}
}
System.out.println("p2 complete");
fileIn.close();
}
}
class Date{
private int month;
private int day;
private int year;
public Date(){
this.month = 1;
this.day = 1;
this.year = 2000;
System.out.println("Empty constructor created.");
}//end Date constructor
public Date(int month, int day, int year){
this.month = month;
this.day = day;
this.year = year;
System.out.println("Overload constructor created.");
}//end Date overload constructor
public void setDate(int month, int day, int year){
//System.out.println("setDate activated: ");
this.month = month;
this.day = day;
this.year = year;
//System.out.println("setDate complete.");
}//end setDate
public void getDate(){
if (month < 10 && !(day < 10)){//if month is the only single digit int
System.out.println("getDate activated: 0" + month + "/" + day + "/" + year);
}//end if
else if (day < 10 && month > 10){//if day is the only single digit int
System.out.println("getDate activated: " + month + "/0" + day + "/" + year);
}//end else if
else if (day < 10 && month < 10){//if both month and day are single digit ints
System.out.println("getDate activated: 0" + month + "/0" + day + "/" + year);
}//end else if
else{
System.out.println("getDate activated: " + month + "/" + day + "/" + year);
}//end else
}//end getDay
public void incrementDay(){
//System.out.println("Test incrementDay: ");
int[] daysPerMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (year % 4 == 0){
daysPerMonth[1] = 29;
}//end if
for (int i = 0; i < 12; i++){
if (i+1 == month && day == daysPerMonth[i]){//if we find the month and day is at the end of the month
if (month == 12 && day == 31){//if we are at december 31st
month = 1;
day = 1;
year += 1;
break;
}//end
else{
month += 1;
day = 1;
break;
}//end else
}//end if
else if (i+1 == month && day < daysPerMonth[i]){
day += 1;
break;
}//end else if
else{
}//end else
}//end for
setDate(month, day, year);
System.out.print("Result of successful increment: ");
getDate();
}//end incrementDay
public void displayDate(){
System.out.print("displayDate activated: ");
System.out.println(this.month + "/" + this.day + "/" + this.year);
}
}//end Date
EVERY next removes one token, so if (fileIn.next().equals("G") && fileIn.next().equals("1")){ reads two tokens if the first token equals G otherwise the if will fail on the first part and NOT read read the second next
So you are better off to put the tokens into variables, like
String tok1 = fileIn.next ();
String tok2 = fileIn.next ();
if (tok1.equals("G") && tok2.equals("1")){
I want to calculate the age of patient. The main issue is the calculation of patients who have born before the start of Java Time. This code works fine in Java console application, but fails in the JSF and JPA based Entity. I only record data of birth in the Entity and Age is a transient property. I can not figure out why the same code not working in Java EE app.
public String getAge() {
System.out.println("getting age");
if (person == null) {
System.out.println("patient is null");
age = "";
return age;
}
if (person.getDob() == null) {
System.out.println("dob is null");
age = "";
return age;
}
System.out.println("this = " + this);
System.out.println("Person = " + Person);
Date dob = person.getDob();
System.out.println("dob = " + dob);
if (dob == null) {
System.out.println("dob is null");
age = "";
return age;
}
long temAge;
long dobTime = dob.getTime();
System.out.println("dobTime = " + dobTime);
long nowTime = Calendar.getInstance().getTime().getTime();
System.out.println("nowTime = " + nowTime);
if (dobTime < 0) {
System.out.println("dobTime = " + dobTime);
temAge = (nowTime + Math.abs(dobTime));
System.out.println("nowTime = " + nowTime);
System.out.println("Math.dob = " + Math.abs(dobTime));
System.out.println("temAge = " + temAge);
temAge = temAge / (1000 * 60 * 60 * 24);
System.out.println("temAge = " + temAge);
System.out.println("age in days before is minus. now age in days is " + temAge);
} else {
temAge = (nowTime - dobTime) / (1000 * 60 * 60 * 24);
System.out.println("age in days before is minus. now age in days is " + temAge);
}
if (temAge < 60) {
age = temAge + " days";
} else if (temAge < 366) {
age = (temAge / 30) + " months";
} else {
age = (temAge / 365) + " years";
}
System.out.println("age is " + age);
return age;
}
Edit :
After going through Kaushal's Answer, I changed my code. It was really easy to work with jodatime. Thanks Kaushal for the help.
public static String getAge() {
LocalDate birthdate = new LocalDate(getDob());
LocalDate now = new LocalDate();
Years ageInYears;
ageInYears = Years.yearsBetween(birthdate, now);
if (ageInYears.getYears() > 0) {
return ageInYears.getYears() + " Years";
} else {
Months ageInMonths = Months.monthsBetween(birthdate, now);
if (ageInMonths.getMonths() > 0) {
return ageInMonths.getMonths() + " Months";
} else {
Days ageInDays = Days.daysBetween(birthdate, now);
return ageInDays.getDays() + " Days";
}
}
}
If possible try using jodatime. Its a very nice utility for dates.
public static void main(String[] args) {
LocalDate birthdate = new LocalDate (1958, 1, 20);
LocalDate now = new LocalDate();
Years age = Years.yearsBetween(birthdate, now);
System.out.println(age.getYears());
}
What do you mean by it fails. Do you get some error or invalid age?
Years years = Years.yearsBetween(new LocalDate(model.getDob()), new LocalDate());
years.getYears();
model.getDob() is java.util object