get untitled column data from CSV file [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 2 years ago.
I have this code, which supposed to retrieve data from CSV file, the file (set of files) structure is as following: [Mary, 7, 17] but the columns are not titled, so I only got A, B, C
when I run the code I seem to have only the first result in the column.
can anybody help me to iterate throw all records?
public void searchFiles()
{
int count = 0;
DirectoryResource c = new DirectoryResource();
int summ = 0;
int currentrow = 0;
String name = "ff";
String k = "Susan";
for(File f : c.selectedFiles())
{
FileResource fr = new FileResource(f);
CSVParser currentFile = fr.getCSVParser(false);
currentrow = 0;
for (CSVRecord row : currentFile)
{
currentrow++;
name = row.get(0);
if(row.get(0) == k)
{
count++;
summ = summ + currentrow;
System.out.println("Row is : " + row.getRecordNumber() + " / " + currentrow);
break;
}
else
{
System.out.println("found");
}
}
System.out.println(count + " / " + currentrow + " / " + name);
}
System.out.println("count is: " + count);
System.out.println("Summ is: " + summ);
System.out.println("Avg is: " + (summ / count));
}

I should use .equals() insted of == in the if statement
if(row.get(0).equals(k))

Related

365 Days Data points store into Arrays over Monthly-Hourly Basis [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have scanned the data from excel to Arraylist but there is all data included under a single place. I have data defined in the above image up to 31st December for every day over the period 7:30 & 8:30. So for each day, there will be 2 rows. hence, 365 days * 2 variable * 8 columns data. And I need to store the data like Month 1 (January) 1st - 31st days of data in different arrays. As I have calculated the mean of 8 columns.
try {
ArrayList<String> GOCIds = new ArrayList<String>();
Workbook workbook = WorkbookFactory.create(new File(SAMPLE_XLSX_FILE_PATH));
for (Sheet sheet : workbook) {
System.out.println("=> " + sheet.getSheetName());
}
Sheet sheet = workbook.getSheetAt(0);
DataFormatter dataFormatter = new DataFormatter();
System.out.println("Excel Data Loading....");
for (Row row : sheet) {
for (Cell cell : row) {
String tempValue = dataFormatter.formatCellValue(cell);
GOCIds.add(tempValue);
}
}
// allMonth
for (int i = 0; i < masterData.size(); i = i + 11) {
allMonth.add(masterData.get(i));
}
System.out.println("Total Month " + allMonth.size());
// allDay
for (int i = 1; i < masterData.size(); i = i + 11) {
allDay.add(masterData.get(i));
}
System.out.println("Total Day " + allDay.size());
// allTime
for (int i = 2; i < masterData.size(); i = i + 11) {
allTime.add(masterData.get(i));
}
System.out.println("Total Time " + allTime.size());
// allDHI
for (int i = 3; i < masterData.size(); i = i + 11) {
allDHI.add(masterData.get(i));
}
System.out.println("Total DHI " + allDHI.size());
// allDNI
for (int i = 4; i < masterData.size(); i = i + 11) {
allDNI.add(masterData.get(i));
}
System.out.println("Total DNI " + allDNI.size());
// allGHI
for (int i = 5; i < masterData.size(); i = i + 11) {
allGHI.add(masterData.get(i));
}
System.out.println("Total GHI " + allGHI.size());
// allDEW
for (int i = 6; i < masterData.size(); i = i + 11) {
allDEW.add(masterData.get(i));
}
System.out.println("Total DEW " + allDEW.size());
// allTemperature
for (int i = 7; i < masterData.size(); i = i + 11) {
allTemperature.add(masterData.get(i));
}
System.out.println("Total Temperature " + allTemperature.size());
// allPressure
for (int i = 8; i < masterData.size(); i = i + 11) {
allPressure.add(masterData.get(i));
}
System.out.println("Total Pressure " + allPressure.size());
// allHumidity
for (int i = 9; i < masterData.size(); i = i + 11) {
allHumidity.add(masterData.get(i));
}
System.out.println("Total Humidity " + allHumidity.size());
// allWS
for (int i = 10; i < masterData.size(); i = i + 11) {
allWS.add(masterData.get(i));
}
System.out.println("Total WS " + allWS.size());
System.out.println("Data Loading Done ^_^");
Can you please guide how can i load monthly-hourly data in 8 different arrays so that I can calculate the means for each of them easily ?
I think first of all you have to load all data from excel file to the model.
public final class Data {
private int month; // [0:11]
private int day; // [1:31]
private long time;
private int dhi;
private int dni;
private int ghi;
private int dewPoint;
private double remperature;
private double pressure;
private double relativeHumidity;
private double windSpeed;
}
public static List<Data> readDataFromExcel(Path xlsx) throws Exception {
try(Workbook workbook = WorkbookFactory.create(Files.newInputStream(xlsx))) {
List<Data> res = new ArrayList<>();
for(Row row : workbook.getSheetAt(0)) {
Data data = new Data();
for(Cell cell : row) {
// fill data
}
res.add(data);
}
return res;
}
}
Then List<Data> allows you to calculate results or group by e.g. day etc.

Why my getName() method is not starting from the first row in my csv file?

public int getRank(int auxYear, String auxName){
//FileResource auxFr = new FileResource("/testing/yob" + auxYear + "short.csv");
String resourceName = "/Users/User/Desktop/coursera/week4_babybirths/babybirths/testing/yob" + auxYear + "short.csv";
File auxFile = new File(resourceName);
if(auxFile.exists()){
FileResource auxFr = new FileResource(auxFile);
//FileResource auxFr = new FileResource();
int auxRank = 0;
for (CSVRecord auxRec : auxFr.getCSVParser(false)){
if (auxRec.get(1).contains(auxGender)){
auxRank += 1;
String auxN = auxRec.get(0);
if (auxRec.get(0).contains(auxName)){
return auxRank;
}
}
}
}
the getName method is reading another csv file and not staring from the first row, below the code :
public String getName(int auxYear, int auxRank, String auxGender){
////FileResource auxFr = new FileResource("/testing/yob" + auxYear + "short.csv");
String resourceName = "/Users/User/Desktop/coursera/week4_babybirths/babybirths/testing/yob" + auxYear + "short.csv";
File auxFile = new File(resourceName);
if (auxFile.exists()){
FileResource auxFr = new FileResource(auxFile);
int auxCount = 0;
for (CSVRecord auxRec : auxFr.getCSVParser()){
String auxStr = auxRec.get(0);
if (auxRec.get(1).contains(auxGender)){
auxCount += 1;
String auxStr1 = auxRec.get(0);
if (auxCount == (auxRank-1)){
return auxRec.get(0);
}
}
}
}
I use also :
public String yourNameInYear(String auxName, int auxYear, int auxNewYear, String auxGender){
int auxRank = getRank(auxYear, auxName, auxGender);
return getName(auxNewYear, auxRank, auxGender);
}
public void testYourNameInYear(){
String auxName = yourNameInYear("Isabella", 2012, 2014, "F");
System.out.println("Isabella" + " born in " + 2012 + " would be " + auxName + " in " + 2014);
}
by default YourNameInYear will call getRank this one will open the yob2012short.csv then after processing, getName will be called and open yob2014short.csv. I don't know why this one is not starting from the first row ?
try to use this
if (auxRec.get(1).contains(auxGender)){
String auxStr1 = auxRec.get(0);
if (auxCount == (auxRank-1)){
return auxRec.get(0);
}
auxCount += 1;
}
as I gess auxCaunt must be your current row so if you increment it from 0 to 1 then you do call the getName with an auxRank equals to 0 (first row may be 0 not 1) so 0 is not equal to 1 so it will loop until auxRank equals 2

Adding different string arrays into List<String[]>, but returning the same value

I am having a database file written to a bus_stopdb.properties file. It looks like this: (This is a part of the file)
2X-bound1-stop0-stopcode=CH42W09500
2B-bound1-stop2-stopseq=2
11C-bound2-stop14-stopname=\u725B\u982D\u89D2\u9435\u8DEF\u7AD9
11D-bounds=2
13D-bound2-stop31-stopcode=SA14S32000
11D-bound1-stop17-stopname=\u89C0\u5858\u78BC\u982D
11D-bound2-stop9-stopcode=KW16W22500
2A-bound1-stop29-stopcode=ME01T11000
14D-bound1-stop18-stopcode=LE01W13000
11X-bound1-stop12-stopseq=12
16-bound1-stop3-stopseq=3
23M-bound1-stop12-stopseq=12
And I am going to load the content of the properties file to a List<String[]>. But I am issuing a problem that is the content of the List is all the same. Here's a function to load the file:
public static boolean loadDatabase(boolean fromClassResources){
try {
File file;
Properties prop = new Properties();
InputStream in;
if (fromClassResources){
in = KmbApi.class.getClassLoader().getResourceAsStream("bus_stopdb.properties");
} else
{
file = new File("bus_stopdb.properties");
if(!file.exists()){
return false;
}
in = new FileInputStream(file);
}
prop.load(in);
int buses = Integer.parseInt(prop.getProperty("buses"));
int bounds;
int stops;
String[] data = new String[5];
for (int i = 0; i < buses; i++){
data[0] = bus_db[i];
bounds = Integer.parseInt(prop.getProperty(bus_db[i] + "-bounds"));
for (int j = 1; j <= bounds; j++){
System.out.println("Bus: " + bus_db[i] + " Bound: " + j);
try {
stops = Integer.parseInt(prop.getProperty(bus_db[i] + "-bound" + j + "-stops"));
} catch (NullPointerException e){
continue;
}
data[1] = Integer.toString(j);
for (int s = 0; s < stops; s++){
data[2] = prop.getProperty(bus_db[i] + "-bound" + j + "-stop" + s + "-stopcode");
data[3] = prop.getProperty(bus_db[i] + "-bound" + j + "-stop" + s + "-stopseq");
data[4] = prop.getProperty(bus_db[i] + "-bound" + j + "-stop" + s + "-stopname");
//Printing the building array
System.out.println(Arrays.deepToString(data));
busstop_pair.add(data);
}
}
}
//Printing the arrays in the List<String[]>
System.out.println(Arrays.deepToString(busstop_pair.toArray()));
in.close();
return true;
} catch (Exception e){
e.printStackTrace();
return false;
}
}
The first println is giving me a correct result (different result).
But the second println is giving me a invaild result, they are all the same!
I couldn't figure out what happened with the code.
You're adding the same array multiple times to the List. You have to create a new array for each iteration of the loop in order to have different elements in your List :
for (int s = 0; s < stops; s++){
data = new String[5];
data[0] = bus_db[i];
data[1] = Integer.toString(j);
data[2] = prop.getProperty(bus_db[i] + "-bound" + j + "-stop" + s + "-stopcode");
data[3] = prop.getProperty(bus_db[i] + "-bound" + j + "-stop" + s + "-stopseq");
data[4] = prop.getProperty(bus_db[i] + "-bound" + j + "-stop" + s + "-stopname");
//Printing the building array
System.out.println(Arrays.deepToString(data));
busstop_pair.add(data);
}

Java writing to a file [duplicate]

This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 9 years ago.
I have a problem with writing to file in Java. I want to write to .txt file but when program writes anything , it deletes before written. I don't want it. I used flw.write before using flw.append but nothing change. Can you help me ?
public void list(String path) throws IOException {
FileWriter flw=new FileWriter(path);
flw.append("----------------------------------------------List---------------------------------------------\n");
for (int i = 0; i < athCtr - 1; i++) {
flw.append("Author:" + athr[i].getId() + "\t"
+ athr[i].getName() + "\t" + athr[i].getUniv() + "\t"
+ athr[i].getDepart() + "\t" + athr[i].getEmail()+"\n");
if (athr[i].getArtCtr() != 0) {
for (int j = 0; j < athr[i].getArtCtr(); j++) {
flw.append("+" + athr[i].getArticle(j) + ":");
for (int k = 0; k < artCtr; k++) {
if (art[k].getPaperId().equals(athr[i].getArticle(j))) {
flw.append("\t" + art[k].getName() + "\t"
+ art[k].getPublisherName() + "\t"
+ art[k].getPublishYear()+"\n");
}
}
}
flw.append("\n");
}
}
flw.append("Author:" + athr[athCtr - 1].getId() + "\t"
+ athr[athCtr - 1].getName() + "\t"
+ athr[athCtr - 1].getUniv() + "\t"
+ athr[athCtr - 1].getDepart() + "\t"
+ athr[athCtr - 1].getEmail()+"\n");
if (athr[athCtr - 1].getArtCtr() != 0) {
for (int j = 0; j < athr[athCtr - 1].getArtCtr(); j++) {
flw.append("+" + athr[athCtr - 1].getArticle(j) + ":");
for (int k = 0; k < artCtr; k++) {
if (art[k].getPaperId().equals(
athr[athCtr - 1].getArticle(j))) {
flw.append("\t" + art[k].getName() + "\t"
+ art[k].getPublisherName() + "\t"
+ art[k].getPublishYear()+"\n");
}
}
}
}
flw.append("----------------------------------------------End----------------------------------------------\n\n");
flw.close();
}
This question should probably be closed as it has been asked and answered many many times, but the key is to use the correct FileWriter constructor, one that takes true as a second parameter. The second true parameter tells Java to open the file for appending rather than overwriting.
//FileWriter flw = new FileWriter(path); // not this
FileWriter flw = new FileWriter(path, true); // but this
And in fact, I am voting to close this question as a duplicate.
As an aside: you'll probably not want to write directly with the FileWriter but rather will want to wrap it in a BufferedWriter or (my preference) a PrintWriter instance. This will allow you to simply and more efficiently write to the file using println(...) and other familiar methods.
Edit 2: After looking more at your code, I think that actually you should consider using a PrintWriter class and then writing with the printf(...) method as this allows for formatted String output, something that works much better than a bunch of tabs as you're trying to do.

How to highlight entire row if any cell is empty in html table

I have created html table in mail body using below code
st = con.createStatement();
rs = st.executeQuery("SELECT nvl(tt.ACTIVITY_NAME,'') as ACTIVITY_NAME, "
+ " nvl(tt.TL_NAME,'') TL_NAME, "
+ " nvl(tt.UW_NAME,'') UW_NAME, "
+ " nvl(tt.TAT_1,'') TAT_1,"
+ " nvl(tt.TAT_2,'') TAT_2, "
+ " nvl(tt.TAT_3,'') TAT_3, "
+ " nvl(tt.TAT_4,'') TAT_4, "
+ " nvl(tt.TAT_4_PLUS ,'') TAT_4_PLUS, "
+ " nvl(tt.g_total ,'') AS GRAND_TOTAL "
+ " FROM uw_activity_tl_uw_tat tt "
+ " WHERE tt.ACTIVITY_NAME = 'First UW' "
+ " ORDER BY tt.TL_NAME,tt.UW_NAME");
StringBuffer sb = new StringBuffer();
ResultSetMetaData rsmd = rs.getMetaData();
int numColumns = rsmd.getColumnCount();
for (int i = 1; i < numColumns + 1; i++) {
String columnName = rsmd.getColumnName(i);
sb.append("<th bgcolor=#fcbe07>" + columnName + "</th>");
}
ArrayList<String> a = new ArrayList<String>();
while (rs.next()) {
a.add(rs.getString(3));
if (rs.getRow() % 2 == 0) {
sb.append("<tr bgcolor=#fcf6cf>");
for (int i = 1; i < numColumns + 1; i++) {
if (rs.getString(i) == null) {
if(i==3)
{
sb.append("<td bgcolor=#fcbe07><b>"+ " "+ "</b></td>");
}
} else {
if (i == 6 || i == 7 || i == 8)
sb.append("<td><FONT COLOR=#ff0000>"
+ rs.getString(i) + "</FONT></td>");
else if(i==3 && (rs.getString(3).equalsIgnoreCase("") || rs.getString(3)==null)){
sb.append("<td bgcolor=#fcbe07><b>"+ rs.getString(i) + "</b></td>");
}else{
sb.append("<td>" + rs.getString(i) + "</td>");
}
}
}
sb.append("</tr>");
} else {
sb.append("<tr>");
for (int i = 1; i < numColumns + 1; i++) {
if (rs.getString(i) == null) {
if(i==3)
{
sb.append("<td bgcolor=#fcbe07><b>"+ " " + "</b></td>");
}
} else {
if (i == 6 || i == 7 || i == 8)
sb.append("<td><FONT COLOR=#ff0000>"
+ rs.getString(i) + "</FONT></td>");
else if(i==3 && (rs.getString(3).equalsIgnoreCase("") || rs.getString(3)==null)){
sb.append("<td bgcolor=#fcbe07><b>"+ rs.getString(i) + "</b></td>");
}else{
sb.append("<td>" + rs.getString(i) + "</td>");
}
}
}
sb.append("</tr>");
}
}
String html = "<html>" + message.getSubject()
+ "</title></head><body><table border=\"1\">"
+ sb.toString() + "</table></body></html>";
message.setContent(html, "text/html");
In the image only one cell is highlighted and I want to highlight the entire row which has any empty cell.Please guide. My query is how to highlight the entire row if any cell is empty.
Short answer: Move the check for the third column and change the <tr> line.
Truthfully, the code you have is a bit of a mess. Personally, I would make the following changes that will make maintence so much easier:
Switch to using classes instead of hard coding bgcolors and so forth.
Set up your system to return associative arrays instead of numeric arrays. That will make reading the code after a lot easier.
Set up intermediate variables to hold the values returned. Do any and all of your calculations and settings things there. THEN dump the entire table-row in one go. That separates your "functional" code from your "display code."
However, in a pinch, something like this will get you going:
tmp = rs.getString(3);
if (tmp == null) {
sb.append("<tr bgcolor=#ffffff>");
} else {
sb.append("<tr bgcolor=#fcf6cf>");
}
BTW - the HTML you generate isn't valid.
Of the top of my head
boolean cellNull = false;
while(rs.next()){
cellNull = false;
cellNull = checkIfAnyFieldIsNull(rs);
if(cellNull)
sb.append("<tr bgcolor=\"#WTH\">");
else
sb.append("<tr>");
//create rest of the row content here
}
private boolean checkIfAnyFieldIsNull(ResultSet rs){
for(i=0 etc..){
if(rs.getString(i) == null)
return true;
}
return false;
}
One way of doing it would be as follows:
Create a POJO class with all the columns that you want to display. Also have a boolean variable, say empty. Set it to true, if any of your column is null
Create a ArrayList and add each instance of your class as you iterate through your resultset
Now use this ArrayList to render your output. Since you already have the boolean variable availabe, you can use this value to set the background color of your row.

Categories