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;
}
Related
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;
}
This question already has answers here:
How to escape % in String.Format?
(3 answers)
Closed 2 years ago.
First, thank you for spending some time on this problem. I've tried based on my own knowledge but can not find out where to modify. I have made a game and in the end, I have to return the formatted string to the terminal.
The exception appeared when I change basic string concatenation to the formatted string. I don't know how to fix it.
players is the player array.
WinRatio is score(int) divided by gamePlayed(int), rounding to integer.
Here is part of my code.
public static void searchAndPrintRankingDataDesc() {
NimPlayer [] players = NimPlayer.getPlayer();
Arrays.sort(players, Comparator.comparing((NimPlayer::getWinRatio)).reversed().thenComparing(NimPlayer::getUserName));
Arrays.stream(players).forEach(System.out::println);
And my toString method:
public String getWinRatio() {
return Integer.toString(Math.round(Float.valueOf(getScore())/ (getGamePlayed())*100));
}
public String toString() {
return String.format( "%02d" +"% | "+ "%02d" +" games | "+ "%s " + "%s", getWinRatio(), gamePlayed, givenName, familyName);
}
% is a special character for String.format, to escape %, you will have to replace it with %%. So your statement becomes-
String.format( "%02d" +"%% | "+ "%02d" +" games | "+ "%s " + "%s", getWinRatio(), gamePlayed, givenName, familyName);
When using % in the formatted string, it has to be escaped using another %. And when formatting the integer value, it will get IllegalFormatConversionException if there has already a toString method.
This code here formatted the integer to string.
public String getWinRatio() {
return Integer.toString(Math.round(Float.valueOf(getScore())/ (getGamePlayed())*100));
}
And the code below formatted again, causing IllegalFormatConversionException.
public String toString() {
return String.format( "%02d" +"% | "+ "%02d" +" games | "+ "%s " + "%s", getWinRatio(), gamePlayed, givenName, familyName);
}
So, the answer will be:
public int getWinRatio() {
return Math.round(Float.valueOf(getScore())/ (getGamePlayed())*100);
}
public String toString() {
return String.format( "%02d" +"%%" + " | "+ "%02d" +" games | "+ "%s " + "%s", getWinRatio(), gamePlayed, givenName, familyName);
}
I have to do the last part of my project which is the payment and receipt part. I'm still clueless of how to do the payment part, but I did try to do the print receipt part. I'm using Netbeans 8.2. The coding below is my print receipt code, it builds successfully but doesn't bear any output. Maybe it's because I have to compile all the other codes like the seat numbers, date, time and all before this could print? Not sure if the reason was because i left the main part empty but I don't know what to put in there tbh.
I'm a beginner coder btw and still have a long long long way to go. I will try my best to understand your explanations. Thank you in advance.
import java.util.Date;
import java.util.Scanner;
public class BusPaymentDetails {
public static void main(String[] args) {
}
class Printpaymentdetails {
public void Printpaymentdetails () {
Date timenow = new Date();
Scanner ticket = new Scanner(System.in);
System.out.println("Your Bus E-Ticket: ");
String date = ticket.nextLine();
System.out.println("Date: " + timenow.toString());
String deptime = ticket.nextLine();
System.out.println("Time of departure: " + deptime);
String arrtime = ticket.nextLine();
System.out.println("Time of arrival: " + arrtime);
String place = ticket.nextLine();
System.out.println("Trip to: " + place);
String buscompany = ticket.nextLine();
System.out.println("Bus Company: " + buscompany);
int seatnumber = ticket.nextInt();
System.out.println("Seat number: " + seatnumber);
double price = ticket.nextDouble();
System.out.println("Price: " + price);
System.out.println("This ticket is non-refundable.");
System.out.println("Please be courteous and do not smoke. Enjoy your trip.");
}
}
}
When running java code, you're invoking a main method, here it is empty, so nothing is run. You would have to add something to the body of this method:
public static void main(String[] args) {
new Printpaymentdetails();
}
This is what I currently have so far
public String toString() {
return this.make + " " + this.model + " " + this.year + " $"
+ this.price + " " + this.mpg;
}
I need to format it to these specifications
Make: left-justified and will be no more than 10 characters long
Model: left-justified starting in column 11 and will be no more than 10 characters long
Year: left-justified and starting in column 21
Price: will be output according to the following money format $99,999.00
MPG: will be output according to the following format: 99.0.
Please help, I'm lost.
Thanks
String.format() is useful for this. It functions similarly to printf in C if you have used it. See http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#format%28java.lang.String,%20java.lang.Object...%29 and http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax
look here:
http://examples.javacodegeeks.com/core-java/lang/string/java-string-format-example/
According to the article, you gotta format like this
return String.format("%s %s %s $%s %s",this.make,this.model,this.year,this.price,this.mpg);
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);