Formatting a Local Date output [duplicate] - java

This question already has answers here:
How to format LocalDate to string?
(7 answers)
Closed 2 years ago.
So, I have a class "Person" that contains a constructor with 4 parameters - 3 Strings and 1 Local Date and an overridden toString method that writes the output onto the console (it also converts the LocalDate variable to a String). Here is the code for that:
public class Person {
String name;
String surname;
LocalDate date;
String placeOfBirth;
Person (String name, String surname, LocalDate date, String placeOfBirth) {
this.name = name;
this.surname = surname;
this.date = date;
this.placeOfBirth = placeOfBirth;
}
public String toString () {
return name + " " + surname + " " + date.toString() + " " + placeOfBirth;
}
}
Now, in the main method, I've created 3 different objects with different parameters and I've added all of them into an ArrayList as follows:
ArrayList lista = new ArrayList();
lista.add(person1.toString());
lista.add(person2.toString());
lista.add(person3.toString());
for (Object data: lista) {
System.out.println(data);
}
The program works fine, and I am getting the output in the following format:
Michael Barton 1968-01-01 Krakov
Now, I would like this date to be displayed as "01. January 1968" instead of "1968-01-01". Is there a way to format that somehow within this code?
Thanks in advance.

You can replace your toString method, with the following example:
public String toString () {
final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd. MMMM yyyy");
return name + " " + surname + " " + date.format(dateFormatter) + " " + placeOfBirth;
}

Related

Reading from CSV file and create object

I'm a complete beginner to Java and I have been given an exercise where I have to read data from a CSV file and then create an object for each line of the file as the program reads the data from the file.
Here is part of the CSV file:
1,Jay, Walker,91 Boland Drive,BAGOTVILLE,NSW,2477
2,Mel, Lowe,45 Ocean Drive,MILLERS POINT,NSW,2000
3,Hugh, Manatee,32 Edgecliff Road,REDFERN,NSW,2016
4,Elizabeth, Turner,93 Webb Road,MOUNT HUTTON,NSW,2290
and so on ...
Here is my code that reads data from the CSV file:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Client_19918424 {
public static void main(String[] args) throws FileNotFoundException {
File inFile = new File("clients.txt");
Scanner inputFile = new Scanner(inFile);
String str;
String[] tokens;
while (inputFile.hasNext()) {
str = inputFile.nextLine(); // read a line of text from the file
tokens = str.split(","); // split the line using commas as delimiter
System.out.println("Client ID: " + tokens[0]);
System.out.println("Client First Name: " + tokens[1]);
System.out.println("Client Sur Name: " + tokens[2]);
System.out.println("Street Address: " + tokens[3]);
System.out.println("Suburb: " + tokens[4]);
System.out.println("State: " + tokens[5]);
System.out.println("Postcode:" + tokens[6]);
System.out.println( );
} // end while
}
}
this is my Client class (have constructor):
public class Client {
private int clientID;
private String firstName;
private String surName;
private String street;
private String suburb;
private String state;
private int postcode;
// constructor
public Client (int ID, String fName, String sName, String str, String sb, String sta, int pCode) {
clientID = ID;
firstName = fName;
surName = sName;
street = str;
suburb = sb;
state = sta;
postcode = pCode;
}
However I don't know how to create a Client object for each line of text file as the program reads data from file.
like for the first line make something like this:
Client client1 = new Client(1, "Jay", "Walker", "91 Boland Drive", "BAGOTVILLE", "NSW", 2477);
And then add it to array:
Client[0] = client1;
can someone help me to solve this question, im really appreciate.
You are almost there.
All that's left to do is to map each token that is already printed to the corresponding fields in the Client class. Since token[0] doesn't really tell what value it holds you could do it in three ways:
while (inputFile.hasNext()) {
str = inputFile.nextLine();
tokens = str.split(",");
// Because tokens[0] is of type String but clientID is of type int,
// we need to parse it and get the integer representation.
int clientID = Integer.parseInt(tokens[0]);
// Both of type String, no parsing required.
String firstName = tokens[1];
String surName = tokens[2];
String street = tokens[3];
String suburb = tokens[4];
String state = tokens[5];
int postcode = Integer.parseInt(tokens[6]);
// Then all that's left to do is to create a new object of `Client` type
// and pass all the gathered information.
Client client = new Client(clientID, firstName, surName, street, suburb, state, postcode);
System.out.println(client + "\n");
}
At this moment if we try to print the client (last line) we will get something like this: com.example.demo.Client#30a3107a. That's because we didn't tell how we want our object to be displayed. For that toString() method in Client class has to be overriden like so:
#Override
public String toString() {
return "Client ID: " + clientID + "\n" + "Client First Name: " + firstName + "\n"
+ "Client Sur Name: " + surName + "\n" + "Street Address: " + street + "\n"
+ "Suburb: " + suburb + "\n" + "State: " + state + "\n" + "Postcode: " + postcode;
}
It will give the exact output that is in your example.
It is achievable to create the class by passing those tokens directly as well, without the creation of temporary variables:
Client client = new Client(Integer.parseInt(tokens[0]), tokens[1], tokens[2], tokens[3], tokens[4], tokens[5], Integer.parseInt(tokens[6]));
This case brings us to the third solution with setters and getters.
The variables that describe the Client are already defined, it is possible to pass them to assemble the perfect object, but it is not possible to retrieve them. Instead of setting the variables directly in the constructor, we can create a special method that will do the job, for instance:
// Other fields omitted
private int clientID;
// The empty constructor required for later usage,
// since right now, we can't create the object without specifying every property.
public Client() {
}
// This method does exactly the same thing that was done before but
// in the constructor directly
public void setClientID(int clientID) {
this.clientID = clientID;
}
// This method will assist in retrieving the set data from above.
public int getClientID() {
return clientID;
}
And then the while loop would look like this instead:
Client client = new Client();
client.setClientID(Integer.parseInt(tokens[0]));
client.setFirstName(tokens[1]);
client.setSurName(tokens[2]);
client.setStreet(tokens[3]);
client.setSuburb(tokens[4]);
client.setState(tokens[5]);
client.setPostcode(Integer.parseInt(tokens[6]));
And to get those values:
System.out.println("Client ID: " + client.getClientID());
Or you could use the constructor with the fields to create the client, add getters in the class, omit both setters, and the empty constructor if the creation of the client should only be possible with all the fields present.

OpenCSV flat to hierarchy structure data parsing

I need advice on the issue which I am facing while parsing CSV data in java.
I have a CSV file with data in below format
name, gender, address_first_line, address_second_line, city, number
me, Male, anonymous, random, Auckland, 6545
other, Female, random, anon, Auckland, 6688
I want to parse the CSV file using the openCSV library in below Object Model. I am aware of parsing single class but facing issues while parsing data when multiple classes are involved. Please suggest if there is any other library available which can help me to get the desired result.
Class User {
String name;
String gender;
Address address;
long number;
}
Class Address {
String firstLine;
String secondLine;
}
univocity-parsers has a #Nested annotation you can use:
Try this:
public static class User {
#Parsed
String name;
#Parsed
String gender;
#Nested
Address address;
#Parsed
long number;
#Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", gender='" + gender + '\'' +
", address=" + address +
", number=" + number +
'}';
}
}
public static class Address {
#Parsed(field = "address_first_line")
String firstLine;
#Parsed(field = "address_second_line")
String secondLine;
#Override
public String toString() {
return "Address{" +
"firstLine='" + firstLine + '\'' +
", secondLine='" + secondLine + '\'' +
'}';
}
}
public static void main(String ... args){
StringReader input = new StringReader(
"name,gender,address_first_line,address_second_line, city,number\n" +
"John,M,Somewhere,Else,City,1");
for(User user : new CsvRoutines().iterate(User.class, input)){
System.out.println(user.toString());
}
}
Output:
User{name='John', gender='M', address=Address{firstLine='Somewhere', secondLine='Else'}, number=1}
If you don't like annotations you can map things manually:
CsvRoutines routines = new CsvRoutines();
ColumnMapper mapper = routines.getColumnMapper();
mapper.attributeToColumnName("name", "name");
mapper.attributeToColumnName("gender", "gender");
mapper.attributeToColumnName("number", "number");
mapper.attributeToColumnName("address.firstLine", "address_first_line");
mapper.attributeToColumnName("address.secondLine", "address_second_line");
for (User user : routines.iterate(User.class, input)) {
System.out.println(user.toString());
}
Hope it helps.
Disclaimer: I'm the author of this lib. It's open-source and free (Apache 2.0 license)

Java : how to get the expression through the jcombo list

How do i create the one line expression using Java swing, link image picture. the every minute, every day,every month, every weekday and every hour need to convert it to "*" and also all the combo box contain the list of number list number link and weekday contain the click the picture
what i want is, if the user select "Every Minute" , "Every day","month = 2", "Weekday = monday", "hour= 3"
note of weekday JCombo : sunday = 0 , monday = 1, tuesday = 2 .....
the output will print as : * * 2 1 3
thanks alot.
i already tried this , my beginning code but cant do much :
String sjcb_EM = jcb_EM.getSelectedItem().toString();
String sjcb_EH = jcb_EH.getSelectedItem().toString();
String sjcb_ED = jcb_ED.getSelectedItem().toString();
String sjcb_EEM = jcb_EEM.getSelectedItem().toString();
String sjcb_EW = jcb_EW.getSelectedItem().toString();
String vb_1 = sjcb_EM + " " + sjcb_EH + " " + sjcb_ED + " " + sjcb_EEM + " " + sjcb_EW;
System.out.println(vb_1);
now i stuck, how to make the expression that i wanted.
Start by building a class which can hold both the display value and the query value...
public class WorkoutUnit {
private String displayValue;
private String queryValue;
public WorkoutUnit(String displayValue, String queryValue) {
this.displayValue = displayValue;
this.queryValue = queryValue;
}
public String getDisplayValue() {
return displayValue;
}
public String getQueryValue() {
return queryValue;
}
#Override
public String toString() {
return displayValue;
}
}
Build a ComboBoxModel using these values...
DefaultComboBoxModel<WorkoutUnit> model = new DefaultComboBoxModel<>();
model.addElement(new WorkoutUnit("Every Minute", "*"));
for (int index = 10; index < 61; index += 10) {
model.addElement(new WorkoutUnit(Integer.toString(index), Integer.toString(index)));
}
JComboBox<WorkoutUnit> cb = new JComboBox(model);
When needed, get the selected item from the combo box and get its query value...
WorkoutUnit unit = (WorkoutUnit)cb.getSelectedItem();
System.out.println("Query = " + unit.getQueryValue());
In this example, I've used toString to provide the display value to the JComboBox, this is not my preferred solution, I'd prefer to use a ListCellRenderer as demonstrated here
Oh, and because it looks like you're heading down a database query route, you should also have a look at Using Prepared Statements

Calendar Class "Normal" Date issue

I am working on a program that will be a basic function for were a user can check something out and the program will calculate a due date which for the sake of simplicity, will be seven days later.
This function is used in other classes and today has been defined as such in the class that uses it
today=Calendar.getInstance();
I am using the Calendar class to do this.
At first I tried this
public Calendar getReturnDate()
{
Calendar dueDate = Calendar.getInstance();
dueDate.set(today.MONTH, today.get(today.MONTH));
dueDate.set(today.YEAR, today.get(today.YEAR));
dueDate.add(today.DATE,today.get(today.DATE + 7));
return dueDate;
}
This gave me a result in which everything was printed down to the millisecond.
So I researched the Calendar class and discovered that a .add method would do the job... or so I thought. Below is the code
public Calendar getReturnDate()
{
Calendar dueDate = Calendar.getInstance();
dueDate.set(today.MONTH, today.get(today.MONTH));
dueDate.set(today.YEAR, today.get(today.YEAR));
dueDate.add(today.DATE,7);
return dueDate;
}
When the function is called in the below code, the print that follows occurs.
public String toString()
{
//Prints them out
String str = "The specs of the book are: ";
str+= "\n\t Title: " + title;
str+= "\n\t Author: " + year;
str += "\n\t checkout date: " + (getReturnDate().MONTH+1) + "/" + getReturnDate().DATE;
return str;
}
The result:
Title: ABC
Author: Suzie Smith
checkout date: java.util.GregorianCalendar[time=1428600973310,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/New_York",offset=-18000000,dstSavings=3600000,useDaylight=true,transitions=235,lastRule=java.util.SimpleTimeZone[id=America/New_York,offset=-18000000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2015,MONTH=3,WEEK_OF_YEAR=15,WEEK_OF_MONTH=2,DAY_OF_MONTH=9,DAY_OF_YEAR=99,DAY_OF_WEEK=5,DAY_OF_WEEK_IN_MONTH=2,AM_PM=1,HOUR=1,HOUR_OF_DAY=13,MINUTE=36,SECOND=13,MILLISECOND=310,ZONE_OFFSET=-18000000,DST_OFFSET=3600000]
As you can see this is not operating correctly. I would like for it to print out month/year when I call this method in the above code.
Does anybody know how to do this or why mine is not working?
Sources:
https://docs.oracle.com/javase/7/docs/api/java/util/GregorianCalendar.html
public String toString() {
Calendar returnDate = getReturnDate();
// Prints them out
String str = "The specs of the book are: ";
str += "\n\t Title: " + title;
str += "\n\t Author: " + year;
str += "\n\t checkout date: " + (returnDate.get(Calendar.MONTH) + 1) + "/" + returnDate.get(Calendar.DATE);
return str;
}

Convertion of user-defined object to string by toString not showing correct output

I have created a class CurrentDate which shows the system date in a particular format(e.g. 29-JUN-12). The class looks like :
package getset;
import java.util.*;
import getset.Getset;
public class CurrentDate{
public static void main(String[] args){
Calendar cal = new GregorianCalendar();
int month = cal.get(Calendar.MONTH);
int year = cal.get(Calendar.YEAR);
int day = cal.get(Calendar.DAY_OF_MONTH);
String toyear=String.valueOf(year);
String newyear=toyear.substring(2,4);
String newmonth=monthvalidation(month);
System.out.println("Current date : " + day + "-" + (newmonth) + "-" + newyear);
}
private static String monthvalidation(int initmonth) {
// TODO Auto-generated method stub
//int initmonth=i;
String finalmonth="";
if(initmonth==1)
{
finalmonth="JAN";
}
if(initmonth==2)
{
finalmonth="FEB";
}
if(initmonth==3)
{
finalmonth="MAR";
}
if(initmonth==4)
{
finalmonth="APR";
}
if(initmonth==5)
{
finalmonth="MAY";
}
if(initmonth==6)
{
finalmonth="JUN";
}
if(initmonth==7)
{
finalmonth="JUL";
}
if(initmonth==8)
{
finalmonth="AUG";
}
if(initmonth==9)
{
finalmonth="SEP";
}
if(initmonth==10)
{
finalmonth="OCT";
}
if(initmonth==11)
{
finalmonth="NOV";
}
if(initmonth==12)
{
finalmonth="DEC";
}
return finalmonth;
}
}
Now when I try to convert it using toString() it does not show what is expected. I tried:
CurrentDate date=new CurrentDate();
String sysdate=date.toString();
System.out.println(""+sysdate);
It shows something like: getset.CurrentDate#18a178a which is not human readable expected format. What can I do to correct this?
You need to override the toString method.
In your CurrentDate class, add somethnig like
#Override
public String toString() {
String toyear=String.valueOf(year);
String newyear=toyear.substring(2,4);
String newmonth=monthvalidation(month);
return day + "-" + newmonth + "-" + newyear;
}
You are not overriding the Object implementation of toString()
To test your method, you could quickly put the logic in that you have developed into a public String toString() method. then in your main method, create a CurrentDate and print the toString.
Override toString method in your class . Add a method like a as follows.
#Override
public String toString() {
return day + "-" + newmonth + "-" + newyear;
}
I see problem in your code.
First, you are not having fields for which you want toString() representation.I think you need to declare fields like:
int month;
int year ;
int day;
#Override
public String toString() {
return "CurrentDate [month=" + month + ", year=" + year + ", day="
+ day + "]";
}
If you are using Eclipse IDE, just generate toString() method, that will be a simple solution to your problem. Right now, object toString() is invoked for your toString(). In fact, as per Josh Bloch,
every class should override toString() for getting human readable format.
CurrentDate date=new CurrentDate();
String sysdate=date.toString();
System.out.println(""+sysdate);
In your above code you are using date object but not assigning any value , only CurrentDate class reference. so your are getting 'getset.CurrentDate#18a178a' when use toString() method.
If you want to format date to string you have to use
public static final String DATE_FORMAT_NOW = "dd-MMM-yy";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);

Categories