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);
Related
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.
I search for a while now, but I didn't found what I need to solve my problem.
First of,I have a "add reminder page" in my app to add reminder with some inputs and the date / time:
<ion-row>
<ion-col>
<ion-label class="ion-label-links" >{{"Datum"|translate}}</ion-label>
</ion-col>
<ion-col text-right>
<ion-label class="ion-label-reminder-rechts">{{"Uhrzeit"|translate}}</ion-label>
</ion-col>
</ion-row>
<ion-row class="schnurr">
<ion-col>
<ion-datetime class="ion-input-reminder" displayFormat="DD.MM.YYYY" [(ngModel)]="reminder.myDate" ></ion-datetime>
</ion-col>
<ion-col>
<ion-datetime text-right class="ion-input-reminder-r" displayFormat="HH:mm" minuteValues="0,5,10,15,20,25,30,35,40,45,50,55" [(ngModel)]="reminder.myTime" ></ion-datetime>
</ion-col>
</ion-row>
And I set a standard date/time with this function:
formatLocalDate() {
var now = new Date(),
tzo = -now.getTimezoneOffset(),
dif = tzo >= 0 ? '+' : '-',
pad = function(num) {
var norm = Math.abs(Math.floor(num));
return (norm < 10 ? '0' : '') + norm;
};
return now.getFullYear()
+ '-' + pad(now.getMonth()+1)
+ '-' + pad(now.getDate())
+ 'T' + pad(now.getHours())
+ ':' + pad(now.getMinutes())
+ ':' + pad(now.getSeconds())
+ dif + pad(tzo / 60)
+ ':' + pad(tzo % 60);
}
Okay, everything is fine. I Save the record in my couchDb and it looks like this:
2017-07-05T09:18:24+02:00
Now the problem with this kind of format is that I implemented a search field but the usual format here is "dd.mm.yyyy" and not the ISO format, so I formated the output in my app like this:
<br><font size="1">{{item.doc.myDate | date:'dd.MM.yyyy, HH:mm'}} Uhr</font>
but if I search for that item, it doesn't work, because the variable is still in the old format.
My search is looking like this:
.....
<ion-item *ngIf="!searchvariable || item.doc.xName.toLowerCase().includes(this.searchvariable)
|| item.doc.myDate.toDateString().includes(this.searchvariable)" class="ion-item1" tappable (click)="openReminder(reminder.doc)" style="background-color: oldlace">
{{item.doc.myDate.toDateString()}}
......
The search is working for everything but the date. (because of the formatproblems)
Is there a possibility to do something like "reminder.myDate.format(xxx)" or something like this?
I mean, it's possible to alter the output, is there a similar way for my search?!
Btw. I have to format the date with this function, otherwise I get errors because the datepicker needs this format.
Thank you!
I have a form with input of type "datetime-local" on a jsp page, the data is passed to a servlet:
String resetTimeString = request.getParameter(RequestParameterName.RESET_TIME);
How to convert the input to java.sql.Timestamp?
EDIT:
Well, I found something new!
You can use Timestamp.valueOf() to format a time-string with the value of yyyy-[m]m-[d]d hh:mm:ss[.f...]
So it can also handle micro/nano seconds. The only thing you need to do is replace the T with a space.
This works:
String datetimeLocal = "1985-04-12T23:20:50.52";
System.out.println(Timestamp.valueOf(datetimeLocal.replace("T"," ")));
The output:
1985-04-12 23:20:50.52
According to this site your resetTimeString looks like this: '1985-04-12T23:20:50.52' (a string)
I couldn't find a method to convert this to a timestamp directly, but you could just split it up manually:
String[] dateTime = datetimeLocal.split("T");
String[] date = dateTime[0].split("-");
String[] time = dateTime[1].split(":");
This will print:
System.out.println("DateTime: " + Arrays.toString(dateTime));
System.out.println("Date: " + Arrays.toString(date));
System.out.println("Time: " + Arrays.toString(time));
>>> DateTime: [1985-04-12, 23:20:50]
>>> Date: [1985, 04, 12]
>>> Time: [23, 20, 50]
After that you could just create a new Timestamp: (This is deprecated!)
Timestamp stamp = new Timestamp(Integer.valueOf(date[0]).intValue() - 1900,
Integer.valueOf(date[1]).intValue(),
Integer.valueOf(date[2]).intValue(),
Integer.valueOf(time[0]).intValue(),
Integer.valueOf(time[1]).intValue(),
Integer.valueOf(time[2].split("\\.")[0]).intValue(),
Integer.valueOf(time[2].split("\\.")[1]).intValue());
Note that, if you use this you need to subtract '1900' from the year and split dots with \\.
Also, you'd need to handle nanoseconds (In my example I'm using the value 50.52 as seconds, but the string returned from your server might not contain the nanoseconds)
You could also calculate a long from the date and use new Timestamp(<long>)
I hope this helps :)
Cyphrags' answer won't work if seconds are set to "00", because Chrome won't send the seconds part resulting in a java.lang.IllegalArgumentException: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff] when calling Timestamp.valueOf().
Therefore a more complete answer could be:
String datetimeLocal = "1985-04-12T23:20";
// make sure the seconds are set before parsing
if (StringUtils.countMatches(datetimelocal, ":") == 1) {
datetimelocal += ":00";
}
Timestamp value = Timestamp.valueOf(datetimeLocal.replace("T", " "));
I am very new to Android and am trying some simple log to get a random background color. I have the code and it returns an integer between 1-256, or so I think. I need to log the value to check if it's OK, but I'm not sure how to log it with Android.. I've been using System.out.println("stuff") to log stuff in the past but I believe that's not how you're supposed to do it in Android.
I have my class:
public static int backgroundColorRandomize()
that returns
return randomRGB;
and I try to log it like this
Log.d(backgroundColorRandomize(), "value = " + randomRGB);
but I need to convert the returned value from backgroundColorRandomize to a String in order for it to log.
I tried java's .toString but I'm not sure I'm using it right.. Any help would be appreciated! Thanks!
Log.d("MYINT", "value: " + randomRGB);
private static final String TAG = YourClass.class.getSimpleName();
...
android.util.Log.d(TAG, String.format("value = %d. random color = %d", randomRGB, backgroundColorRandomize()));
More info:
http://developer.android.com/reference/android/util/Log.html
https://developer.android.com/tools/debugging/debugging-log.html
Logging libraries: https://android-arsenal.com/tag/57
I prefer String.valueOf(value).
Log.d(String.valueOf(backgroundColorRandomize()), "value = " + randomRGB);
Log.d(backgroundColorRandomize() + "" /* <-- all you need. */, "value = " + randomRGB);
I use
Log.d("MYINT", "value: " + randomRGB.toString());
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.