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);
Related
Here's what I'm trying to do:
String output = "If you borrow" + currencyFormatter.format(loanAmount);
+" at an interest rate of" + rate + %;
+"\nfor" + years;
+",you will pay" + totalInterest + "in interest.";
Take out the semicolons before the end of your concatenation.
String output = "If you borrow" + currencyFormatter.format(loanAmount)
+" at an interest rate of" + rate + "%"
+"\nfor" + years
+",you will pay" + totalInterest + "in interest.";
I also recommend that you move the concatenation operator to the end of the line rather than the start of the line. It's a minor stylistic preference...
String output = "If you borrow" + currencyFormatter.format(loanAmount) +
" at an interest rate of" + rate + "%" +
"\nfor" + years +
",you will pay" + totalInterest + "in interest.";
Finally, you may notice that you are missing some white-spaces when you try printing that string. The String.format method helps with that (also see the documentation for Formatter). It's also faster than doing lots of concatenations.
String output = String.format(
"If you borrow %s at an interest rate of %d%%\nfor %d years, you will pay %d in interest.", currencyFormatter.format(loanAmount), rate, years, totalInterest
);
I have a class that parses ZonedDateTime objects using.split() to get rid of all the extra information I don't want.
My Question: Is there a way to use square brackets as delimiters that I am missing, OR how do I get the time zone ([US/Mountain]) by itself without using square brackets as delimiters?
I want the String timeZone to look like "US/Mountian" or "[US/Mountian]
What I've Tried:
Ive tried wholeThing.split("[[-T:.]]?) and wholeThing.split("[%[-T:.%]]") but those both give me 00[US/Mountain]
I've also tried wholeThing.split("[\\[-T:.\\]]) and wholeThing.split("[\[-T:.\]") but those just give me errors.
(part of) My Code:
//We start out with something like 2016-09-28T17:38:38.990-06:00[US/Mountain]
String[] whatTimeIsIt = wholeThing.split("[[-T:.]]"); //wholeThing is a TimeDateZone object converted to a String
String year = whatTimeIsIt[0];
String month = setMonth(whatTimeIsIt[1]);
String day = whatTimeIsIt[2];
String hour = setHour(whatTimeIsIt[3]);
String minute = whatTimeIsIt[4];
String second = setAmPm(whatTimeIsIt[5],whatTimeIsIt[3]);
String timeZone = whatTimeIsIt[8];
Using split() is the right idea.
String[] timeZoneTemp = wholeThing.split("\\[");
String timeZone = timeZoneTemp[1].substring(0, timeZoneTemp[1].length() - 1);
If you want to parse the string yourself, use a regular expression to extract the values.
Don't use a regex to find characters to split on, which is what split() does.
Instead, use a regex with capture groups, compile it using Pattern.compile(), obtain a Matcher on your input text using matcher(), and check it using matches().
If it matches you can get the captured groups using group().
Example regex:
(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}).(\d+)[-+]\d{2}:\d{2}\[([^\]]+)\]
In a Java string, you have to escape the \, so here is code showing how it works:
String input = "2016-09-28T17:38:38.990-06:00[US/Mountain]";
String regex = "(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2}).(\\d+)[-+]\\d{2}:\\d{2}\\[([^\\]]+)\\]";
Matcher m = Pattern.compile(regex).matcher(input);
if (m.matches()) {
System.out.println("Year : " + m.group(1));
System.out.println("Month : " + m.group(2));
System.out.println("Day : " + m.group(3));
System.out.println("Hour : " + m.group(4));
System.out.println("Minute : " + m.group(5));
System.out.println("Second : " + m.group(6));
System.out.println("Fraction: " + m.group(7));
System.out.println("TimeZone: " + m.group(8));
} else {
System.out.println("** BAD INPUT **");
}
Output
Year : 2016
Month : 09
Day : 28
Hour : 17
Minute : 38
Second : 38
Fraction: 990
TimeZone: US/Mountain
UPDATED
You can of course get all the same values using ZonedDateTime.parse(), which will also ensure that the date is valid, something none of the other solutions will do.
String input = "2016-09-28T17:38:38.990-06:00[US/Mountain]";
ZonedDateTime zdt = ZonedDateTime.parse(input);
System.out.println("Year : " + zdt.getYear());
System.out.println("Month : " + zdt.getMonthValue());
System.out.println("Day : " + zdt.getDayOfMonth());
System.out.println("Hour : " + zdt.getHour());
System.out.println("Minute : " + zdt.getMinute());
System.out.println("Second : " + zdt.getSecond());
System.out.println("Milli : " + zdt.getNano() / 1000000);
System.out.println("TimeZone: " + zdt.getZone());
Output
Year : 2016
Month : 9
Day : 28
Hour : 17
Minute : 38
Second : 38
Milli : 990
TimeZone: US/Mountain
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;
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I have write the following toString() methode
public String toString() {
return "Product: "+ this.productName + ", Barcode: " + this.barCode
+ ", Expiration Date: " + this.expirationDate.toString() + ", Customer Price: "
+ this.customerPrice + ", Shops Price: " + this.shopsPrice
+ ", Instore Amount: " + this.inStoreAmount + ", Sale: "
+ (this.sale == null) ? "Not on sale" : + this.sale.toString();
}
But there is a problem with the way I use the if statement.
eclipse: "cannot covert from string to boolean"
You had an issue with the balancing of concatenation operator +. Also, I edited your method to be the following:
public String toString() {
return "Product: "+ this.productName + ", Barcode: " + this.barCode
+ ", Expiration Date: " + this.expirationDate.toString() + ", Customer Price: "
+ this.customerPrice + ", Shops Price: " + this.shopsPrice
+ ", Instore Amount: " + this.inStoreAmount + ", Sale: "+ ((this.sale == null) ? "Not on sale" : this.sale.toString());
}
When you are writing IF-ELSE short hand, try to keep everything in a (...) set of parentheses to keep track of things easily. I don't care what other professionals say about this, but if this helps you to understand things, so be it!
This is illegal syntax
(this.sale == null) ? "Not on sale" : + this.sale.toString()
and a compilation error should have alerted you to this problem.
Instead, use
((this.sale == null) ? "Not on sale" : this.sale.toString())
I've placed the entire ternary operator into parentheses to be clear.
I want to format some numbers in our jsp pages.
first i define some resources in my porperties
format.number.with2Decimal={0,number,#0.00}
......
Question1:
i want to know what is the ‘#’ and '0' means?
0.00,#0.00,##.00,###0.00
who can tell me the differences between them? thanks!
Question2:
if i define a BigDecimal type in my action
BigDecimal number1;
Then my page should using a format to show this value,
1.if number1=null then show -NIL-
2.if number1=0 then show -NIL-
3.if number1>0 then show 1.00,3434.98 .....
please ignore number<0
Question3:
change number1 to a String,
1.if number1=null or empty or blank then show -NIL-
2.if number1=Hello then show Hello ....
could you give me help?
Here you go :
<s:property value="getText('{0,number,#,##0.00}',{profit})"/>
This is how I format numbers in my projects. You can use it with <s:if> to attain what you require.
Question1: i want to know what is the ‘#’ and '0' means?
0.00,#0.00,##.00,###0.00 who can tell me the differences between them? thanks!
0 means that a number must be printed, no matter if it exists
# means that a number must be printed if it exists, omitted otherwise.
Example:
System.out.println("Assuming US Locale: " +
"',' as thousand separator, " +
"'.' as decimal separator ");
NumberFormat nf = new DecimalFormat("#,##0.0##");
System.out.println("\n==============================");
System.out.println("With Format (#,##0.0##) ");
System.out.println("------------------------------");
System.out.println("1234.0 = " + nf.format(1234.0));
System.out.println("123.4 = " + nf.format(123.4));
System.out.println("12.34 = " + nf.format(12.34));
System.out.println("1.234 = " + nf.format(1.234));
System.out.println("==============================");
nf = new DecimalFormat("#,000.000");
System.out.println("\n==============================");
System.out.println("With Format (#,000.000) ");
System.out.println("------------------------------");
System.out.println("1234.0 = " + nf.format(1234.0));
System.out.println("123.4 = " + nf.format(123.4));
System.out.println("12.34 = " + nf.format(12.34));
System.out.println("1.234 = " + nf.format(1.234));
System.out.println("==============================");
Running Example
Output:
Assuming US Locale: ',' as thousand separator, '.' as decimal separator)
==============================
With Format (#,##0.0##)
------------------------------
1234.0 = 1,234.0
123.4 = 123.4
12.34 = 12.34
1.234 = 1.234
==============================
==============================
With Format (#,000.000)
------------------------------
1234.0 = 1,234.000
123.4 = 123.400
12.34 = 012.340
1.234 = 001.234
==============================
In Struts2, you can apply this kind of format with the getText() function from ActionSupport.
P.S: Question 2 and 3 are trivial (and messy).