Formatting a return string - java

I am trying to format this return string to display ratings at one decimal place.
return String.format(title + "," + genre + "," + releaseYear + "(" + (getRating() == -1 ? "No ratings" : getRating()) + "): " + numOfDeaths + " deaths");
I keep getting an error saying too few parameters passed.

You want java.text.DecimalFormat.
DecimalFormat df = new DecimalFormat("0.0##");
String result = df.format(getRating());
return String.format(title + "," + genre + "," + releaseYear + "(" + (getRating() == -1 ? "No ratings" : result) + "): " + numOfDeaths + " deaths");

Related

how to simulate Excel control codes in String

One web project I'm involved in requires generating a CSV to the user.
One field is notes and there can be multiple notes in the field, separated by a return (alt-enter in Excel), appearing as
A USER entered on 02/17/2023: Test note
A USER entered on 02/17/2023: This is another note
Is it possible to insert control codes into a Java string that Excel will pick up and format the cell properly?
For what it's worth, this was my attempt:
}else if (formType.equalsIgnoreCase("downloadCSV")) {
Date d = new Date();
String filename = "C:/temp/rtTmp" + d.getTime() + ".csv";
File f = new File(filename);
List<Contact> contactList = RetentionTrackDatabaseUtil.getContacts();
BufferedWriter bw = new BufferedWriter(new FileWriter(f));
bw.write("name,"
+ "gender,"
+ "age,"
+ "DOB,"
+ "DOH,"
+ "DOR,"
+ "DOS,"
+ "dateContact,"
+ "reason,"
+ "status,"
+ "empNum,"
+ "shift,"
+ "phone,note(s)\n");
for (Contact c : contactList) {
System.out.println(c.getAge());
bw.append("\"" + c.getName() + "\"" + ","
+ c.getGender() + ","
+ Integer.toString(c.getAge()) + ","
+ (c.getDOB()!=null?RetentionTrackUtil.sdf.format(c.getDOB()):"") + ","
+ (c.getDOH()!=null?RetentionTrackUtil.sdf.format(c.getDOH()):"") + ","
+ (c.getDOR()!=null?RetentionTrackUtil.sdf.format(c.getDOR()):"") + ","
+ (c.getDOS()!=null?RetentionTrackUtil.sdf.format(c.getDOS()):"") + ","
+ (c.getDateContact()!=null?RetentionTrackUtil.sdf.format(c.getDateContact()):"") + ","
+ c.getReason() + ","
+ c.getStatus() + ","
+ c.getEmpNum() + ","
+ c.getShift() + ","
+ c.getPhone() + ",");
for(Note n: c.getNoteList()){
bw.append("(" + n.getEnteredBy() + " on " + RetentionTrackUtil.sdf.format(n.getNoteDate()) + ")" + n.getNote() + "\\n");
}
bw.append("\n");
}
bw.close();
sendFile(response, filename);
}

problem while using database column value into Date() sqlite android

i have small problem, i googled it many times but i couldn't get it...
i'm using a query (sqlite) to retrieve some data ..
in this query their is Date() used to increase certain date dynamic number of days (coming from column in the same table) ..
if i put this days static (1,2,3,.....) it works fine but if i put column name it doesn't.
this query fails and i want it to work:
String selectQuery = "SELECT DISTINCT * FROM " + TABLE_NAME + " WHERE "
+ DATE + " = date('" + targetDate + "',' " + REPETITIONS + " day') ";
this works fine :
String selectQuery = "SELECT DISTINCT * FROM " + TABLE_NAME + " WHERE "
+ DATE + " = date('" + targetDate + "','2 day') ";
where
targetDate: date entered by user to get events of that date
DATE: date of every event in the table
REPETETIONS: dynamic number (column in the same table)
the problem is using REPETITIONS in the date function...
create statement
String SQL_CREATE_EVENT_TABLE = "CREATE TABLE " + TABLE_NAME + " ( " +
ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
TITLE + " TEXT ," +
DATE + " TEXT , " +
IS_NOTIFY + " INTEGER , " +
NOTIFICATION_TIME + " TEXT ," +
REPEAT + " INTEGER ," +
REPEAT_DURATION + " INTEGER ," +
REPETITIONS + " INTEGER ," +
CERTAIN_DATE + " TEXT ," +
NOTE + " TEXT ," +
IS_SPOKEN + " INTEGER " +
" );";
and this is the selecting statement
String selectQuery = "SELECT DISTINCT * FROM " + TABLE_NAME + " WHERE " + DATE + " = '" + targetDate
+ "' OR (( " + REPEAT + " = '1' AND " + REPEAT_DURATION + " = '0' ) AND " + DATE + " <= '" + targetDate + "')"
+ " OR( " + REPEAT + " = '1' AND " + REPEAT_DURATION + " = '3' ) AND " + DATE + " <= '" + targetDate + "' AND " + CERTAIN_DATE + " >= '" + targetDate + "'"
+ " OR (" + REPEAT + " = '1' AND " + REPEAT_DURATION + "= '2' ) AND " + targetDate + " >= '" + DATE + "' AND "+ targetDate+ " <= date('" + DATE + "','" + REPETITIONS + " days')";
The variable REPETITIONS in this statement:
String selectQuery = "SELECT DISTINCT * FROM " + TABLE_NAME + " WHERE "
+ DATE + " = date('" + targetDate + "',' " + REPETITIONS + " day') ";
should be a number and not a column name.
The date function in SQLite has various syntaxes but you use this one:
SELECT date('2014-10-23','+7 day');
you must supply a number before day.
Edit try this:
String selectQuery = "SELECT DISTINCT * FROM " + TABLE_NAME + " WHERE "
+ DATE + " = date('" + targetDate + "', " + REPETITIONS + " || ' day') ";
In sqlite date() function, the NNN days is a string modifier and not an expression. Therefore you cannot use column names or even || string concatenation there.
You can format the modifier string in your code and place it in the SQL. This requires additional query to the database, which is likely not what you want.
If you can assume each day is 24 hours (which is not always true, consider e.g. DST events), you could try something like
... date(strftime('%s', '" + targetDate + "', " + REPETITIONS + "*24*60*60, 'unixepoch') ...
where strftime('%s', ...) converts to seconds and date(..., 'unixepoch') converts back to datestamp.
But seriously I'd consider redesigning the schema to better support your functional requirements.

Writing to file from an array

I've been trying to write a method in java to write data from an array to a text file but I'm getting two errors.
public void WriteStudentDetailsToFile() {
PrintWriter out = null;
try {
out = new PrintWriter("StudentDetails.txt");
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage());
System.out.println("in " + System.getProperty("user.dir"));
System.exit(1);
}
for (int i = 0; i < enrolment.length; i += 1) {
if (enrolment[i] != null) {
Student a = this.enrolment[i];
if (a.getName().equals("") || a.getAddress().equals("") || a.getDOB().equals("") || a.getGender().equals("")) {
break;
} else {
String record = a.getName() + "\t" + "0" + "\t" + a.getAddress() + "\t" a.getDOB() + "\t" + a.getGender();
out.println(record);
}
}
}
}
}
The two errors are
C:\Users\B00661059\Downloads\Assignment 2\Assignment 2\Student_Enrolment.java:137: error: ';' expected
String record = a.getName() + "\t" + "0" + "\t" + a.getAddress() + "\t" a.getDOB() + "\t" + a.getGender();
^
C:\Users\B00661059\Downloads\Assignment 2\Assignment 2\Student_Enrolment.java:137: error: not a statement
String record = a.getName() + "\t" + "0" + "\t" + a.getAddress() + "\t" a.getDOB() + "\t" + a.getGender();
On line 137, you need to add a concatenation operator (+) here:
"\t" + a.getDOB()
The most obvious error is that you are missing a plus here: + "\t" a.getDOB() +.
It should be
String record = a.getName() + "\t" + "0" + "\t" + a.getAddress() + "\t" + a.getDOB() + "\t" + a.getGender();
You might also want to look into how to define and use a toString() function in your Student class to control the string representation of the object.
Try this :
String record = a.getName() + "\t" + "0" + "\t" + a.getAddress() + "\t" + a.getDOB() + "\t" + a.getGender();
instead of this :
String record = a.getName() + "\t" + "0" + "\t" + a.getAddress() + "\t" a.getDOB() + "\t" + a.getGender();
Also this doesn't make sense :
if (a.getName().equals("") || a.getAddress().equals("") || a.getDOB().equals("") || a.getGender().equals("")) {
break;
}
Since you are only interested in the else branch you can negate it.
if !(a.getName().equals("") || a.getAddress().equals("") || a.getDOB().equals("") || a.getGender().equals("")) {
// Do what you want
}

How to split a NAME and ADDRESS, and print them separately

I'm starting with this String:
"NAME-RAHUL KUMAR CHOUDHARY ADDRESS-RAJDHANWAR DISTRICT-GIRIDIH STATE-JHARKHAND PIN CODE-825412"
I want to split the name and address, and print it like this:
NAME:RAHUL KUMAR CHOUDHARY , DDRESS-RAJDHANWAR DISTRICT-GIRIDIH STATE-JHARKHAND PIN CODE-825412. like this
This is what I have so far:
String str_colArow3 = colArow3.getContents();
//Display the cell contents
System.out.println("Contents of cell Col A Row 3: \""+str_colArow3 + "\"");
if(str_colArow3.contains("NAME"))
{
}
else if(str_colArow3.contains("ADDRESS"))
{
}
String string = "NAME-RAHUL KUMAR CHOUDHARY ADDRESS-RAJDHANWAR DISTRICT-GIRIDIH STATE-JHARKHAND PIN CODE-825412";
String[] parts = string.split("-");
string = "Name: " + parts[1].substring(0, parts[1].length() - 7)
+ "\nAdress: " + parts[2] + " - " + parts[3]
+ "\nPin Code: " + parts[5];
Something like this. Check out the split() method for strings, your string is a bit poorly formatted to use this, though. You have to adjust for your own needs.
Edit: Better way to do this, with different string input.
String string = "RAHUL KUMAR CHOUDHARY:RAJDHANWAR:GIRIDIH:JHARKHAND:825412";
String[] parts = string.split(":");
string = "Name: " + parts[0] + "\n"
+ "Address: " + parts[1] + "\n"
+ "District: " + parts[2] + "\n"
+ "State: " + parts[3] + "\n"
+ "Pin Code: " + parts[4] + "\n";

How to write a carriage return into xls file in Java

I would like to insert a carriage return into a cell of a xls file.
So I have written this code
address = rs.getString(16) + " " + rs.getString(17) + "
"
+ rs.getString(18) + " " + rs.getString(19) + " (" +
rs.getString(20) + ")";
"writer.write("<ss:Cell><ss:Data ss:Type=\"String\">" + address + "</ss:Data></ss:Cell>");`
but in the Excel File the result is that the carriage return is replaced with a "square symbol". In which mode can I resolve this issue?
Thanks,
Stefano
In excel, to enter a new line in a cell, you need to insert ASCII characters 13 + 10 (constant CrLf on this page : http://msdn.microsoft.com/en-us/library/f63200h0%28v=vs.80%29.aspx).
Have you tried:
String crLf = Character.toString((char)13) + Character.toString((char)10);
address = rs.getString(16) + " " + rs.getString(17) + crLf
+ rs.getString(18) + " " + rs.getString(19) + " (" +
rs.getString(20) + ")";

Categories

Resources