I have a date of birth in string in Date class and I want to call it as Date variable in another class using constructor, HealthProfile as per my uml diagram. How can I do that? And also, what is the Scanner input type for Date? I have done other parts and below code is my getDateString method in Date class.
public String getDateString()
{
String dob = String.valueOf(day) + month + String.valueOf(year);
return dob;
}
The date of birth format I was trying to print is, example: 8 October 2000. I have a txt file of such data and trying to call from it.
java.util.Scanner hasn’t got a method for reading an instance of your Date class (it may be obvious). I suggest that you use
nextInt() for reading the day of month (e.g., 8)
next() for reading the month name (e.g., October)
nextInt() for reading the year (e.g., 2000)
With the three values thus obtained you can call your constructor Date(int day, String month, int year). As you may know, a Scanner can read from a text file.
Aside from this (ignore if you can’t use it):
For the conversion back to a string I suggest that you put spaces between the elements to get like 8 October 2000 again rather than 8October2000, which is unpleasant to read.
One may consider an enum for the months. It will complicate input, but will provide validation that a correct month name is entered. If this is not part of your requirement, you may leave this comment for other readers.
For production work one would use LocalDate from java.time, the modern Java date and time API, and not develop one’s own Date class.
Link: Oracle tutorial: Date Time explaining how to use java.time.
I help you to create a Date Class with a contruct method.
In main class, i help you to use System.in to input data string and return what you method want.
Date Class:
public class Date {
int year;
String month;
int day;
public Date(int year, String month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
/**
* Getter and Setter methods
*/
public String getDateString(){
String dob = String.valueOf(day) + month + String.valueOf(year);
return dob;
}
Test main class:
public static void main(String[] args) throws ParseException {
Scanner scanner = new Scanner(System.in);
String inputstr = scanner.nextLine(); //you enter 24-07-2020
String[] inputarr = inputstr.split(" ");
Date date = new Date(Integer.valueOf(inputarr[2]), inputarr[1], Integer.valueOf(inputarr[0]));
System.out.println(date.getDateString());
}
Related
I need to create a method that will display the date in format mm/dd/yyyy when the method is accessed through a printf statement. This is an assignment and I cannot use java.util.Date Class.
The date value must be returned through the method so it can be printed with
System.out.printf("Date 1 is %s%n%n", date1.displayDate())
I have tried converting the instance variables for month, day, and year to Strings and then putting the String values into an array but when I do that all I'm getting is the first value of each of the indexes printed into the returned value.
I need to have the whole date in format mm/dd/yyyy returned but I'm not sure if I can iterate the entire array and then save that value into a variable to return.
Here is my driver class...
public class DriverClass {
public static void main(String[] args) {
//--------------------------------------------------------------------------------------
// DATE CLASS FUNCTIONALITY TEST
//--------------------------------------------------------------------------------------
DateClass date1 = new DateClass(07,21,1987);
DateClass date2 = new DateClass(01, 22, 1999);
DateClass date3 = new DateClass(04,17,1945);
System.out.printf("Date 1 is %s%n%n", date1.displayDate());
System.out.printf("Date 2 is %s%n%n", date2.displayDate());
System.out.printf("Date 3 is %s%n%n", date3.displayDate());
}
}
Here is my code...
public class DateClass {
private int month;
private int day;
private int year;
public DateClass(int monthIn, int dayIn, int yearIn){
month=monthIn;
day=dayIn;
year=yearIn;
}
//get and set methods
public int getMonth(){
return month;
}
public void setMonth(int month){
this.month=month;
}
public int getDay(){
return day;
}
public void setDay(int day){
this.day=day;
}
public int getYear(){
return year;
}
public void setYear(int year){
this.year=year;
}
public String[] displayDate(){
String sMonth = Integer.toString(month);
String sDay = Integer.toString(day);
String sYear = Integer.toString(year);
String dayAR[] = new String[5];
dayAR[0] = sMonth;
dayAR[1] = "/";
dayAR[2] = sDay;
dayAR[3] = "/";
dayAR[4] = sYear;
return dayAR;
}
}
Your displayDate() method should return a String instead of a String[].
return sMonth + "/" + sDay + "/" + sYear;
This won't quite work though, you would also need to do some bounds checking so that the values can be padded with zeros. For instance you want 01/01/0001 not 1/1/1.
I would avoid implementing a bunch of bounds checking though, just use an existing tried-and-true method for formatting strings. I suggest using String.format(format, ...args) to do the heavy lifting unless explicitly disallowed.
return String.format("%02d/%02d/%04d", month, day, year);
This solution still isn't perfect, it doesn't account for values that are not valid, but that should be done when the values are being set, not when the string is being generated.
You can use String.format to help get the formatting right. For example:
String.format("%d/%d/%d", 1, 20, 1995); // Produces "1/20/1995"
The documentation for Java String format syntax (like the %d and %s) is here.
You'll probably want to prefix days and months with a zero if they are only a single digit.
(Just wanted to give a hint since this is an assignment but let me know if you get stuck)
I want to create a student record using a method that is able to
take input from user about student details . My class Student should
consists of following fields : short semester,
full name,
registration number etc
.registration number of a student = concatenation of year and student number.
Eg year at which student joined = 2023,
student no. = 80,
So registration number = 2380
Plus I have been tasked to input date using class GregorianCalendar
INSIDE STUDENT CLASS:
import java.util.*;
class Student2{
String fullname;
GregorianCalendar date;
short semester;
Student2()
{
}
Student2(String name,short sem, GregorianCalendar Date)
{
fullname = name;
semester=sem;
date = Date;
}
int years = date.get(Calendar.YEAR);
String year = Integer.toString(years);
String Studno = Integer.toString(80);
String y1= year.substring(0,3);
String Reg = y1.concat(Studno);
int reg = Integer.parseInt(Reg);
void Studarry()
{
int n=5,i;
Student2[] stuarry = new Student2[10];
for(i=0;i<n;i++)
{
System.out.println("Enter name sem year month day gpa cgpa\n");
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
short sem2 = sc.nextShort();
int year2 = sc.nextInt();
int month2 = sc.nextInt();
int day2=sc.nextInt()
GregorianCalendar gc2 = new GregorianCalendar(year2,month2,day2);
stuarry[i] = new Student2(name,sem2,gc2);
}
}
void Display()
{
}
}
INSIDE DRIVER CLASS:
public class Greg2{
public static void main(String[] args)
{
Student2 starr = new Student2();
starr.Studarry();
}
}
ERRORS :
Exception in thread "main" java.lang.NullPointerException
at oop2/lab5.Student2.<init>(Greg2.java:23)
at oop2/lab5.Greg2.main(Greg2.java:68)
Class name versus variable name
date = Date;
Date with an uppercase D is the name of a class, not a variable. Instead you should have defined the name of the argument being passed as date not Date. This line becomes date = date ;. The compiler can distinguish between the argument and the member variable. If you want more clarity for the reader, you can say this.date = date ;.
But that is a poor name for a variable. Because there is indeed two classes bundled with Java named Date, both related to GregorianCalendar, I suggest avoiding the use of date as a variable name for GregorianCalendar object – just too confusing.
java.time
The GregorianCalendar is a terrible class. It was supplanted entirely years ago by the java.time classes. Specifically, ZonedDateTime. Both classes represent a moment as seen through the wall-clock time of some particular region (a time zone).
However, both classes are not meant for your purpose. You want only a date, without a time-of-day and without the context of a time zone or offset-from-UTC. So LocalDate fits your needs.
LocalDate ld = LocalDate.of( year , month , day ) ;
Constructor
int years = date.get(Calendar.YEAR);
String year = Integer.toString(years);
String Studno = Integer.toString(80);
…
These lines are floating around, not placed inside a method. They should have been put inside the constructor of your method.
Why is there a class named Greg2? Did you mean a specific student? If so, Greg should be represented by values assigned to an instance of a Student class.
What is with all the 2 characters at the end of names? Naming is important; get that straight and you will be half-way to a solution.
So most of this code is a mess. Try again from scratch. Look up other code examples, such as on Stack Overflow, in the Oracle Tutorial, or in the textbook for your class of this homework assignment.
Learn about separation of concerns. One class should be just about representing a student. Another class should represent your app, and hold the main method. Use a Collection to gather the newly instantiated Student classes into a roster, possibly making a class Roster if you have other roster-related responsibilities.
Lastly, take baby steps. Add one little thing at a time, see that it runs properly. Use System.out.println to verify values. Do not try to write all the code at once.
Your NullPointerException comes from this line:
int years = date.get(Calendar.YEAR);
Field initializers like this one are executed before the constructor. So when you create a Student2 object using new Student2(), the above line is created while the date field is still null, and therefore the call to date.get() throw the exception.
Instead move the initialization of years into the constructor, after you have assigned an object to date.
As others have said too, the GregorianCalendar class is poorly designed and long outdated. If it wasn’t for a lazy teacher apperently with no clue of what has been going on with Java the last more than 5 years, you shouldn’t use it. Never ever.
Mistakes corrected as-
1) Bought field initializers inside my constructor to get rid of NullpointerException as said by ( Basil Bourque , Ole V.V. )
2) created array of student objects in main and called method Stduarry on them .
3) Variable name Date changed to gc
import java.util.*;
INSIDE STUDENT CLASS:
class Student22{
String fullname;
GregorianCalendar date;
short semester;
int reg;
Student22()
{
}
Student22(String name,short sem, GregorianCalendar gc)
{
fullname = name;
semester=sem;
date = gc;
int years = date.get(Calendar.YEAR);
String year = Integer.toString(years);
System.out.println(year);
String Studno = Integer.toString(80);
String y1= year.substring(2,4);
System.out.println(y1);
String Reg = y1.concat(Studno);
System.out.println(Reg);
reg = Integer.parseInt(Reg);
System.out.println(reg);
}
void Studarry(int n)
{
System.out.println("Enter name sem year month day \n");
Scanner sc = new Scanner(System.in);
fullname = sc.nextLine();
System.out.println(fullname);
semester = sc.nextShort();
int year2 = sc.nextInt();
int month2 = sc.nextInt();
int day2=sc.nextInt();
GregorianCalendar gc2 = new GregorianCalendar(year2,month2,day2);
date= gc2;
int years = date.get(Calendar.YEAR);
String year = Integer.toString(years);
String Studno = Integer.toString(n);
String y1= year.substring(0,3);
String Reg = y1.concat(Studno);
reg = Integer.parseInt(Reg);
Display();
}
void Display()
{
System.out.println(fullname);
System.out.println(semester);
System.out.println(reg);
System.out.println(date.get(Calendar.YEAR));
}
}
INSIDE DRIVER CLASS:
public class Greg2{
public static void main(String[] args)
{
System.out.println("Please enter a Firstname , MiddleName & Lastname separated by spaces");
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
GregorianCalendar gc = new GregorianCalendar(2018,7,22);
Student22 s = new Student22(name,(short)3,gc);
s.Display();
int i,j,n;
System.out.println("Enter n\n");
n = sc.nextInt();
Student22[] starr = new Student22[n+1];
for(j=1;j<=n;j++)
{
starr[j]= new Student22();
starr[j].Studarry(j);
}
}
}
This question already has answers here:
Take int of day, month, year and convert to DD/MM/YYYY
(2 answers)
Closed 4 years ago.
I want the date to display together with forward slash without any space. If I run the below program, it will only display month's value. Please help.
int month, day, year;
public int displayDate()
{
int date = month/day/year;
}
System.out.printf("Date: %d%n", d.displayDate());
Simplistic Answer
You can use a String to append three int values
e.g.
int month, day, year;
public String displayDate()
{
return String.format ("%d/%d/%d", month,day, year);
}
System.out.printf("Date: %s%n", d.displayDate()); // change this as well
Of course this code has no bound checking
In your code, you are dividing month, day and year with the operator /.
In Java, there is a class SimpleDateFormat to format and display dates.
Try the following code:
public String displayDate(int month, int date, int year) {
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, date);
return new SimpleDateFormat("MM/dd/yyyy").format(calendar.getTime());
}
It will return your date in the format MM/dd/yyyy as a String.
Note that month is zero-based.
Check this link out to get some more information about the format: https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
As the documentation clearly states, Character.getNumericValue() returns the character's value as a digit.
It returns -1 if the character is not a digit.
If you want to get the numeric Unicode code point of a boxed Character object, you'll need to unbox it first:
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateDemo {
public static void main(String[] args) {
DateDemo d = new DateDemo();
System.out.printf(d.displayDate()); //Output: 04/04/2018
}
public String displayDate()
{
String date = new SimpleDateFormat("dd/MM/yyyy").format(new Date());
return date;
}
}
I've been given an assignment where I need to create a set of interfaces and classes for a car rental company. I'm busy working on implementing a LicenceNumber class which must match the following spec:
The licence number has three components. The first component is the concatenation of the initial of the first name of the driver with the initial of the last name of the driver. The second component is the year of issue of the licence. The third component is an arbitrary serial number. For example, the string representation of the licence number for a licence issued to Mark Smith in 1990 would have the form, MS-1990-10, where the 10 is a serial number that, with the initials and year, guarantees the uniqueness of the licence number as a whole.
You should use the java.util.Date class to represent dates. However, you must not use deprecated methods of the Date class. So, for example, in your test classes use java.util.Calendar to construct dates of birth and dates of issue of licences. You can assume default time zone and locale. (Note, there are now better classes available in the java.time package which was introduced in Java 1.8 but it will be good experience to work with classes
which are written less well).
So far I've got the following implementation for the LicenceNumber class:
import java.util.Calendar;
import java.util.Date;
public class LicenceNumber {
private String licenceNo;
public LicenceNumber(Name driverName, Date issueDate){
setLicenceNo(driverName, issueDate);
}
public String getLicenceNo() {
return licenceNo;
}
public void setLicenceNo(Name driverName, Date issueDate) {
String initials;
initials = driverName.getForename().substring(0, 1) + driverName.getSurname().substring(0,1);
System.out.println(initials);
int issueYear = issueDate.getYear(); //Deprecated
}
}
I want to be able to get only the year from issueDate, but the only way I can figure out how to do it, is by using the deprecated method, getYear(). This is obviously against the criteria, so can anyone shed some light on how to get the Year from a Date object without using deprecated methods?
Thanks ahead.
Try this
Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
int year = localDate.getYear();
Here is fix
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
System.out.println(calendar.get(Calendar.YEAR));
Substitute the new date with the date you are wanting to get the year from.
I can think of three ways to obtain the year from a Date object but avoiding the deprecated methods. Two of the approaches use other Objects (Calendar and SimpleDateFormat), and the third parses the .toString() of the Date object (and that method is not deprecated). The .toString() is potentially locale specific, and there could be issues with the approach in other locales, but I am going to assume (famous last words) that the year is always the only sequence of 4 digits. One could also understand the specific locale and use other parsing approaches. For example, standard US/English puts the year at the end (e.g., "Tue Mar 04 19:20:17 MST 2014"), one could use the .lastIndexOf(" ") on the .toString().
/**
* Obtains the year by converting the date .toString() and
* finding the year by a regular expression; works by assuming that
* no matter what the locale, only the year will have 4 digits
*/
public static String getYearByRegEx(Date dte) throws IllegalArgumentException
{
String year = "";
if (dte == null) {
throw new IllegalArgumentException("Null date!");
}
// match only a 4 digit year
Pattern yearPat = Pattern.compile("^.*([\\d]{4}).*$");
// convert the date to its String representation; could pass
// this directly, but I prefer the intermediary variable for
// potential debugging
String localDate = dte.toString();
// obtain a matcher, and then see if we have the expected value
Matcher match = yearPat.matcher(localDate);
if (match.matches() && match.groupCount() == 1) {
year = match.group(1);
}
return year;
}
/**
* Constructs a Calendar object, and then obtains the year
* by using the Calendar.get(...) method for the year.
*/
public static String getYearFromCalendar(Date dte) throws IllegalArgumentException
{
String year = "";
if (dte == null) {
throw new IllegalArgumentException("Null date!");
}
// get a Calendar
Calendar cal = Calendar.getInstance();
// set the Calendar to the specific date; the reason why
// Calendar is deprecated is this mutability
cal.setTime(dte);
// get the year using the .get method, and convert to a String
year = String.valueOf(cal.get(Calendar.YEAR));
return year;
}
/**
* Uses the SimpleDateFormat with a format for only a year.
*/
public static String getYearByFormatting(Date dte)
throws IllegalArgumentException
{
String year = "";
if (dte == null) {
throw new IllegalArgumentException("Null date!");
}
// set a format only for the year
SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
// format the date; the result is the year
year = sdf.format(dte);
return year;
}
public static void main(String[] args)
{
Calendar cal = Calendar.getInstance();
cal.set(2014,
Calendar.MARCH,
04);
Date dte = cal.getTime();
System.out.println("byRegex: "+ getYearByRegEx(dte));
System.out.println("from Calendar: "+ getYearFromCalendar(dte));
System.out.println("from format: " + getYearByFormatting(dte));
}
All three approaches return the expected output based upon the test input.
Take a look at https://docs.oracle.com/javase/8/docs/api/java/text/DateFormat.html and related classes. That can yield a string with just the "year" field from a given 'Date'.
I am trying to split a string into different array indexes. This string is coming from user input (through java.util.Scanner) and is being loaded into a String variable. How can I split the input from the string into different array indexes?
Also, how can I do the math functions that are implied by DOBbeing an int?
Here is my code:
import java.util.Scanner;
public class main {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter date of birth (MM/DD/YYYY):");
String DOB;
DOB = input.next();
int age = 0;
age = 2013 - DOB - 1;
int age2 = 0;
age2 = age + 1;
System.out.println("You are " + age + " or " + age2 + " years old");
}
}
String[] parts = DOB.split("/");
int months = Integer.parseInt(parts[0]);
int days = Integer.parseInt(parts[1]);
int years = Integer.parseInt(parts[2]);
Then just use years instead of DOB in your calculations.
Better yet, use new Calendar() to get today's precise date, and compare against that.
Use DateTimeFormat as shown in Parse Date String to Some Java Object to parse your string into a DateTime object, and then access the members.
DateTimeFormatter format = DateTimeFormat.forPattern("MM/dd/yyyy");
DateTime dateTime = format.parseDateTime(DOB);
This uses Joda Time library.
Alternatively you can use SimpleDateFormat in a similar manner, to parse it into a Date object.
I notice you're using keyboard input to recognize the string. If the user doesn't input what you expect it will crash your program. (If you're just starting Java, this is fine; you can just run it again)
You can make it easier to split by asking them thrice too eg:
int dob[] = new Integer[3]; // integer array made from Integer class-wrapper
System.out.println("Input day");
dob[0] = Integer.parseInt(input.next());
System.out.println("Input month");
dob[1] = Integer.parseInt(input.next());
System.out.println("Input year");
dob[2] = Integer.parseInt(input.next());
You now have three integers in an array, split and ready to manipulate.
If Integer can't parse the text input as a number you'll get a NumberFormatException.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
public class main {
public static void main(String args[]) {
// Man you should look onto doing your
// homework by yourself, ijs.
// But here it goes, hope i make myself clear.
Scanner input = new Scanner(System.in);
System.out.println("Enter date of birth (MM/DD/YYYY):");
String DOB;
DOB = input.next();
//
int age;
// You need to know when it is today. Its not 2013 forever.
java.util.Calendar cal = java.util.Calendar.getInstance();
// ^ The above gets a new Calendar object containing system time/date;
int cur_year = cal.get(Calendar.YEAR);
int cur_month = cal.get(Calendar.MONTH)+1; // 0-indexed field.
// Cool we need this info. ill skip the day in month stuff,
// you do that by your own, okay?
SimpleDateFormat dfmt = new SimpleDateFormat("MM/dd/yyyy");
int bir_year;
int bir_month;
try {
// If you wanna program, you must know that not all functions
// will exit as it's intended. Errors happen and YOU should deal with it.
// not the user, not the environment. YOU.
Date d = dfmt.parse(DOB); // This throws a parse exception.
Calendar c = Calendar.getInstance();
c.setTime(d);
bir_year = c.get(Calendar.YEAR);
bir_month = c.get(Calendar.MONTH)+1; // 0-indexed field;
age = cur_year - bir_year;
// Well, you cant be a programmer if you dont think on the logics.
if(cur_month < bir_month ) {
age -= 1;
// If the current month is not yet your birth month or above...
// means your birthday didnt happen yet in this year.
// so you still have the age of the last year.
}
// If code reaches this point, no exceptions were thrown.
// and so the code below wont execute.
// And we have the variable age well defined in memory.
} catch(ParseException e) {
// But if the date entered by the user is invalid...
System.out.println("The date you typed is broken bro.");
System.out.println("Type a date in the correct format MM/DD/YYYY and retry.");
return; // Got errors? tell the program to quit the function.
}
// Well now we can say to the user how old he is.
// As if he/she didnt know it ^^'
System.out.println(String.format("You are %d years old", age));
// **Not tested.
}
}