Formatting output/Justifying field of width - java

I have to left-justify the station names and right-justify the number results in the example below for an assignment, ie Vegan Station needs to be left-justified in a field of width 15, but when I try it gives me an error for the %2d for the result. If anyone could help me understand how to correctly format it I'd really appreciate it.
System.out.printf("\n" + "\n" + "You rated each station as follows");
System.out.printf("\n" + "%-15s, Vegan Station" + "%2d", vegan);
System.out.printf("\n" + "Pasta Station " + "%2d" , pasta);
System.out.printf("\n" + "Waffle Station " + "%2s", waffle + "\n");
Here's the error:
java.util.MissingFormatArgumentException: Format specifier '%2d'
at java.util.Formatter.format(Formatter.java:2519)
at java.io.PrintStream.format(PrintStream.java:970)
at java.io.PrintStream.printf(PrintStream.java:871)
at Survey.main(Survey.java:127)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

You're messing up your quotes. It should be:
System.out.printf("%n%-15s%2d", "Vegan Station", vegan);
Keep the format String together as a single String, and the variables to follow in a comma-delimited list.
Also for new lines, don't use \n but rather use %n when using printf.

Related

Shift the value to the right in Excel when opening the csv file

I am trying to shirt the values with leading zero to the right when opening the csv file with Excel MS. I am using bufferedWriter.write("\\"\t"+row[4] + "\\"\t"); . The tabe and quote to display the leading zero since without it I am just getting 46 and not 046.
if(row[4].startsWith("0")){
bufferedWriter.write(";" + "\\"\t"+row[4] + "\\"\t");
}else{
bufferedWriter.write(";" + row[4]);
}
screen shot
Couple of things:
Fix the write line to properly escape the quote
bufferedWriter.write(";" + "\"\t"+row[4] + "\"\t");
This is the output (I am using the pipe/"|" instead of a new line)
2016;" 046" |2016;" 046" |2016;400|2016;400|
Remove the second tab to get rid of the extra space in your display
bufferedWriter.write(";" + "\"\t"+row[4]);
This is now the output
2016;" 046"|2016;" 046"|2016;400|2016;400|

ERROR: extra data after last expected column When trying to inserting csv file

I am trying to insert csv file in postgresql database using java
the code is
CopyManager copyManager = new CopyManager((BaseConnection) conn);
FileReader fileReader = new FileReader(filename);
copyManager.copyIn("COPY meta.fk_payment_temp(\n"+
"settlement_ref_no, order_type, fulfilment_type, seller_sku, wsn, \n" +
" order_id, order_item_id, order_date, dispatch_date, delivery_date, \n" +
" cancellation_date, settlement_date, order_status, quantity, order_item_value, \n" +
" refund, protection_fund, total_marketplace_fee, service_tax, \n" +
" settlement_value, commission_rate, commission, fee_discount, \n" +
" cancellation_fee, fixed_fee, emi_fee, total_weight, shipping_fee, \n" +
" reverse_shipping_fee, shipping_zone, token_of_apology, pick_and_pack_fee, \n" +
" storage_fee, removal_fee, invoice_id, invoice_date, invoice_amount, \n" +
" sub_category, total_offer_amount, my_offer_share, flipkart_offer_share)\n" +
" FROM STDIN with csv header delimiter ','", fileReader );
there is 41 column in csv file and as well as in table
the error detail is:
Where: COPY fk_payment_temp, line 2:
"NFT-150331087GN00107XXXXXXX,prepaid,NON-FA,BD46-157,,OD102411813209536003,166288248,"Mar
25, 2015","..."
as we seen error is in "Mar 25, 2015" but the data is
NFT-150331087GN00107XXXXXXX prepaid NON-FA BD46-157 OD102411813209536003 166288248 25-Mar-15 26-Mar-15 27-Mar-15 31-Mar-15 delivered 1 339 339 0 0 -85.26 -10.54 243.2 15 -50.86 0 0 -5 0 0.3 -29.4 0 LOCAL 0 0 0 0 IN27248 26-Mar-15 309 babydoll 0 0 0
how i can solve this ?
My experience is that this is almost always caused by malformed csv data. There really is no substitute for knowing the format, how to review material for proper escaping, etc. And CSV is not simple. There are lots of rules regarding things like embedded end of line characters and the like.
A good place to start (if you hadn't already found your answer) would be running the data through a spreadsheet and see what seems to end up on the wrong columns.

Java printf error when using asterisks

Here's the printf statement that's giving me the error:
System.out.printf("%-*s%*s", dateTimeWidth, dateTime, locationWidth, location);
I want dateTime to be printed left-aligned with width dateTimeWidth and location to be printed right-aligned with width locationWidth. Both locationWidth and dateTimeWidth are passed in as ints.
Here's the error I'm getting:
Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = '-'
at java.util.Formatter.checkText(Formatter.java:2503)
at java.util.Formatter.parse(Formatter.java:2485)
at java.util.Formatter.format(Formatter.java:2414)
at java.io.PrintStream.format(PrintStream.java:920)
at java.io.PrintStream.printf(PrintStream.java:821)
at TicketMaker.drawTicket(TicketMaker.java:43)
at TicketMaker.main(TicketMaker.java:12)
I believe something is wrong with my syntax, but I'm not sure what I'm doing wrong.
Info on printf with asterisks
here
Declare an extra variable before using printf:
String format = "%-" + dateTimeWidth + "s%" + locationWidth + "s";
System.out.printf(format, dateTime, location);

String concatenation in java is not working on one system

I believe that most of you would be thinking that this is the same question you have heard multiple times (and answered ) about string concatenation in Java. But trust me, it is different. In fact, so different that I am even hesitant in posting it here. But anyways, here it is. I have some piece of code which goes like:
public void handleSuccess(String result)
{
result = result.trim();
MessageBox.alert("Information","Result after trimming: '" + result + "'");
result = result.substring(result.indexOf('\n') + 1);
MessageBox.alert("Information","Result after substring: '" + result + "'");
String returns = getReturns();
MessageBox.alert("Information","Returns: '" + returns + "'");
String action = getAction();
MessageBox.alert("Information","Action: '" + action + "'");
String finalResult = result + returns + action;
MessageBox.alert("Information","Final result: '" + finalResult + "'");
}
Now the situation here is that, all of these : getReturns(), result and getAction() return non blank values, and in fact the string finalResult contains the concatenated value after the last line is executed.
So, at Line 1, "result" contains "12/03/2013|04-AERTY|". The value of result remains same at end of line 1,2. getReturns() returns value 12.4724. So at end of line 3, finalResult contains "12/03/2013|04-AERTY|12.4724". getAction() returns "expt". So, at end of line 5, finalResult contains "12/03/2013|04-AERTY|12.4724|expt"
This is , when I debug or run the application in eclipse. As soon as build the same application on a UNIX system to generate a "war" file, and deploy the war on a tomcat server, the problem rears it's ugly head. When I run the application on the deployed war, the last line does not contain the concatenated value. So at the end of line 5, finalResult contains just "12/03/2013|04-AERTY|12.4724". I expected it to contain "12/03/2013|04-AERTY|12.4724|expt" as it does while running in eclipse.
I have tried stringbuffer, stringbuilder and the "+" operator as well, but nothing seems to work. I am not even getting an exception.
Can somebody help me in fixing this or at least enlightening me in what I might be doing wrong here?
Just to stress again, the code on eclipse(which is on a windows machine) and UNIX machine are exactly same. I have done a diff on them.
Here is what I get after putting the message-boxes:
Message-box 1: "Result after trimming: '12/03/2013|04-AERTY|'"
Message-box 2: "Result after substring: '12/03/2013|04-AERTY|'"
Message-box 3:"Returns: '12.4724'"
Message-box 4:"Action: '|expt'"
Message-box 5:"Final result: '12/03/2013|04-AERTY|12.4724|expt'"
Message-box 5 output is the one I receive when I execute code using eclipse
When running on deployed war, Message-box 1-4 have the same output as above, but Message-box 5 says: "Final result: '12/03/2013|04-AERTY|12.4724"
It's not clear where the extra "|" is meant to come from - if getAction() just returns expt, the result would be 12/03/2013|04-AERTY|12.4724|expt.
Anyway, I think it's safe to say that string concatenation will be working fine, and something else is wrong. You should add more diagnostics, logging everything:
public void handleSuccess(String result) {
result = result.trim();
log.info("Result after trimming: '" + result + "'");
result = result.substring(result.indexOf('\n') + 1);
log.info("Result after substring: '" + result + "'");
String returns = getReturns();
log.info("Returns: '" + returns + "'");
String action = getAction();
log.info("Action: '" + action + "'");
// It's not clear what this is meant to do. I suggest you remove it and
// use logging instead.
MessageBox.alert("Information", "The selected action is " + action, null);
String finalResult = result + returns + action;
log.info("Final result: '" + finalResult + "'");
I suspect you'll find that action is an empty string in the broken case.
Note that I've added quotes round each of the logged values, very deliberately. That means that if there's some unprintable character at the end of a string which causes problems, you should be able to detect that in the logging.
EDIT: As per the comment thread, when these were turned into message boxes (as it turns out this is running in GWT) it looks like there's something wrong with the early strings, as the closing ' isn't seen in diagnostics, in the broken case. The OP is going to investigate further.

java: default number-formatting

I have a program that does algorithmic calculations with some number-output. I want this output to look nice and the program still being fast. I used the DecumalFormat but this makes it so slow, but works.
Is there a way to set the default number output so I wouldnt need DecimalFormat???
Locale deLocale = new Locale("de_DE");
// should be format: ###,###.### 123.456,789 de_DE
Locale.setDefault (deLocale);
double f=-123456.123458998;
System.out.println (""+f+""); // I wourld expect -123.456,123
// but the output is -123456.123458998
any ideas?? thanks!
chris
You need to look at the Customizing Format.
You need a ###,###.### - de_DE pattern.
String pattern= "###,###.###";
DecimalFormat myFormatter = new DecimalFormat(pattern);
double f=-123456.123458998;
String output = myFormatter.format(f);
System.out.println(f+ " " + pattern + " " + output);
EDIT : Use Predefined format, in case you don't want your own pattern.

Categories