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);
}
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;
}
I want to pun a condition in an multidimesional array and I'm stuck. My method should return a name in a specific format. If find a title like (Mr.,Mrs) return Title , first letter from name , and the full surname. If title is not found return full name + full surname. Eg. Ms. S. T. Mark or Smith T. Rose or Tony Mark.
String[][] names = {
{"Mr. ", "Mrs. ", "Ms. ","Miss"},
{"Smith ", "Jones "},
{"Tony ", "Jhon "},
{"Mark ","Rose "}
};
if (names[0].equals(names)&& names[1].equals(names)&&names[2].equals(names)&& names[3].equals(names)){
return names[0][0] + names[1][0].substring(0,1)+". " + names[2][0].substring(0,1)+". "+names[3][0];}
return"";
As I wrote in the comment this doesn't make sense:
names[0].equals(names)
names[0] is string array (String[]) containing: {"Mr. ", "Mrs. ", "Ms. ","Miss"}
While names is array of string arrays (String[][]) containing everything, so you can't compare them in such way, it will always be false.
Moreover you actually shouldn't ever use equals for arrays. Please check this post for more information:
https://stackoverflow.com/a/8777266/7624937
Now, as suggested by #Tschallacka you should probably create Person class, e.g:
class Person {
String title;
String name;
String surname;
}
and then implement functions which are of your interest. So according to your description such function would look like this:
public String introduceYourself() {
if (title != null) {
return title + " " + name.charAt(0) + " " + surname;
} else {
return name + " " + surname;
}
}
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;
}
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);
having quite some trouble with the following regex.
String fktRegex ="public double " + a+ "2" + b + "(double value) {return value * (.*);}\n";
a and b are Strings that are inserted individually.
The regex works just fine until I want to identify also the number with it. That's the (.*) part...
Any help`? Would be really glad! Thanks.
C.
Judging by your example I think you need to escape few regex meta-characters like { } ( ) * so your regex should probably look more like
"public double " + a + "2" + b + "\\(double value\\) \\{return value \\* (.*);\\}\n";
Demo
// abc2xyz
String a = "abc";
String b = "xyz";
String fktRegex = "public double " + a + "2" + b + "\\(double value\\) \\{return value \\* (.*);\\}\n";
String data = "public double abc2xyz(double value) {return value * 100000;}\n";
Pattern p = Pattern.compile(fktRegex);
Matcher m = p.matcher(data);
if(m.find()){
System.out.println(m.group(1));
}else{
System.out.println("no match found");
}