Split an excel content and display in console ignore Blank Cell - java

In my Excel cell I've data as below. And it is in a single cell.
01/2015 to present
02/2010 - 04/2010
01/2008 - 12/2009
I want to split this cell and display result as
Date 1 - 01/2015 to present
Date 2 - 02/2010 - 04/2010
Date 3 - 01/2008 - 12/2009
I'm not sure of how many different lines of data will be in a single cell. There may be up to 10 Lines, then it should print the same like in the below format
Date (counter) - (Date Value)
Thanks for the hint #Saurabh
I'm using the below code now. and able to print the dates in the above format.
if (!covDate.equals(null) || !(covDate == "")|| !(covDate == null) || !covDate.equals(""))
{
String[] date = covDate.split("\\n");
for(int i=0;i<parts.length; i++){
System.out.println("Date "+ i + " - "+date[i])
}
}
else{
System.out.println("Dates Missing");
}
Here Basically I've 2 columns in my Excel and in the second column I've these dates. And there are instances where in there is data in first column but data is missing in Dates column. And there it is throwing me a null pointer Exception Also in my eclipse my else block is showing error as a dead block
please let me know how can i fix these.
Thanks

I have simplified your test expression below, the date variable inside the for loop is replaced with parts :
if (covDate != null && !covDate.equals(""))
{
String[] parts = covDate.split("\\n");
for(int i=0;i<parts.length; i++){
System.out.println("Date "+ i + " - "+parts[i])
}
}
else{
System.out.println("Dates Missing");
}

Firstly, you should not such a long ternary operator, instead you can use, StringUtils.isEmpty(object) ..
This is available in org.apache.maven.shared.utils.StringUtils. Once you have this, you can read the object to this method, and perform accordingly.
Secondly, coming to second column, you can try, if(StringUtils.isEmpty(cellValue)) if this gives you true, then go ahead and split the string, else continue.

Related

Java / Kotlin getting value in for loop for step + one and also a step before if condition in for loop

I am currently creating a program to check the order status (pending or confirmed) when a user open the app now the problem is if I need to check after order time and between I am checking time (Current Time) in this timeframe check for how many times I change price and compare if price is match or not.
So how can I check a step before i. like i is 3 and I need to also include 2 in it and compare value of i and i+1 value in every loop without getting index out of bond.
Code :
for (i in 0 until arrTriple!!.size){
if (arrTriple[i].third >= ordertime){ //arrTriple[i].third is time when when I change price
//Need this value also without getting indexoutofbond = arrTriple[i+1].third
//So I can use my logic here.
}
}
Think I understand what you're asking. Can you start with i = to 1 and do i-1 instead of i+1? Something like this:
for (i in 1 until arrTriple!!.size) {
if (arryTriple[i-1].third >= overtime {
arrTriple[i].third
}
}
You'll have an edge case where arrTriple.size == 1 that you'd need to handle still.
EDIT:
Otherwise, just add an if-check.
for (i in 0 until arrTriple!!.size){
if (arrTriple[i].third >= ordertime && (i+1) < arrTriple.size){
}
}
You don't necessarily need until. You would write it just like this
for(element in arrTriple!!){
if(element.third >= ordertime){
// Your logic here
}
}
This would be my approach

How should I format my return statement so I don't double the answer?

private String twoDigits(int value) {
String result = "";
{
if ((mMinute >= 0) && (mMinute <= 9) && (mSecond >= 0) && (mSecond <= 9)) {
tempmin = ("0" + mMinute );
tempsec = ("0" + mSecond );
} else
tempmin = (mMinute + "");
tempsec = (mSecond + " ");
return tempin+tempsec;
This just doubles the output that I'm looking for and I was wondering, whether or not the issue was with the return statement or the actual method.
I need to call back to this method, twoDigits(mMinute)+":"+twoDigits(mSecond) to get the code to display the time, but instead of being able to display 10:09:08 I keep displaying 10:0908:0908
I was wondering how I should fix my code.
Since there are a lot of tiny mistakes in your code, I'll suggest a slightly different approach. Not sure if this method works, in what I assume is Java, but give it a shot:
private String twoDigits(int value)
{
return value <= 9 ? "0" + value : value;
}
This is actually an if/else abbreviation. Return the following: If value <= 9 then add a zero before the value, else the value.
If there's a risk of negative values being received, you could add this:
return (value >= 0 && value <= 9) ? "0" + value : value;
First, there's Paul's comment about the {} after else to encompass both rows. Then, you are not actually using the value received by the function but rather some global variables (mMinute and mSecond). You create but never use result. Furthermore, your if statement says that if both mMinute AND mSecond are between 0 and 9 then both should be fixed. Since you should use value you only have to check that variable's range and edit it accordingly. On the row tempsec = (mSecond + " "); you add a space.. mistake? Finally, you misspelled tempmin on the return row.
Good luck.
Note that your method has a value parameter. You should use this rather than directly access the fields in your class. Perhaps it might help for you to think about the purpose of the twoDigits() method. It seems to me that it is supposed to take an int value and pad it with a leading zero if the input is only a single digit. Note that my description in the previous sentence does not refer to the member variables that represent minutes and seconds; it only refers to the input value.

I'm getting a StringOutOfBoundsException in part of a java Project

else if (args.length == 5)
{
String firstyear = args[3];
String secondyear = args[4];
String datayear = temp[0];
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date first = df.parse(firstyear);
Date second = df.parse(secondyear);
Date datas = df.parse(datayear);
weekday = convertDateToWeekDay(temp);
if (weekday == day || day == 0);
{
if (temp[8].contentEquals(drawtype)
|| drawtype.contentEquals("A")) {
if ((datas.equals(first)) || (datas.equals(second))
|| ((datas.after(first)) && (datas.before(second)))) {
if (choice == 1 || choice == 2) {
for (int count = 0; count < jackpot.length; count++) {
jackpot[count] = Integer
.parseInt(temp[count + 1]);
jackpotnumbers[jackpot[count] - 1]++;
}
}
if (choice == 2) {
bonus = Integer.parseInt(temp[7]);
if (temp[8].contentEquals(drawtype)
|| drawtype.contentEquals("A"))
bonusnumbers[bonus - 1]++;
}
}
}
}
}
}
This is a piece of a project I have to do for college. Its purpose is to analyse lotto information between two dates and for different draws. It is giving this error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
It takes in two dates from the command line.It reads a line from a file and puts it into an array called temp. The rest of the program works fine but if it goes into this part it crashes and gives that error. Can anyone spot what's causing the error. I also know I can write this better, but I want it to work first before I focus on making it good code.
Edit: bonusnumbers and jackpotnumbers are both int arrays that are 45 long.temp is a string array with the temp[0] being a date such as 10/07/1994.jackpot is an int array that is 45 long.
if(weekday == day || day == 0); this is to check that that date read from the file is a certain day supplied by the user.
I dont know what you mean by stack trace or use the debugger.I am new to programming
edit 2: I know that the error is in this section because it only crashes when I run this section.I can run the other parts of the code without it crashing.After this error it just says the name of each method
You mention that you're "new to programming" so you don't "know what [is meant] by stack trace or use the debugger". How, then, do you know that it is this chunk of code that is causing the problem? You must've seen something in the console of your IDE (assuming you're using an IDE or perhaps you're running this from the command-line? In either case, there should've been a lot lines of text immediately after the one you posted saying things like "at java...". Anyway, if that is present, then that is your stacktrace (basically, the lines of execution of your program that led up to your StringIndexOutOfBoundsException).
Regardless, since it is throwing a StringIndexOutOfBoundsException, I would say your contentEquals(...) method calls are highly suspect. But, as others have stated, it is impossible to say without more information.

Java - Modulus - Adding from one table to another

I have a JTable of which one column is pre-filled with 30min time slots (6.30-24.00).
Now I have another table which has a list of movie titles which contains a column with the duration of the movie (in minutes - e.g. 140 minutes).
Now I have a button that does this. I made a piece of code, which funnily enough, sometimes works and sometimes doesn't (after I add 3-4 titles). It adds to the time slots according to the math equation.It gives me :
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "DRAMA"
This is the code:
btnAddProg.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
int dur = Integer.parseInt(progTableModel.getValueAt(listTable.getSelectedRow(), listTable.getSelectedColumn()+1).toString()) / 30;
int durT = Integer.parseInt(progTableModel.getValueAt(listTable.getSelectedRow(), listTable.getSelectedColumn()+1).toString());
if(durT % 30 != 0)
{
dur += 1;
}
for(int i = 0; i < dur; i++)
{
String value = progTableModel.getValueAt(listTable.getSelectedRow(), listTable.getSelectedColumn()).toString();
String value2 = progTableModel.getValueAt(listTable.getSelectedRow(), listTable.getSelectedColumn()+2).toString();
channel1DataTitle.set(chOneTable.getSelectedRow()+i, value);
channel1DataGenre.set(chOneTable.getSelectedRow()+i, value2);
}
chOneTable.repaint();
} catch (IndexOutOfBoundsException f) {
JOptionPane.showMessageDialog(frame,
"Please select a row in the Channel table!",
"Channel row not selected",
JOptionPane.PLAIN_MESSAGE);
}
}
});
Can anyone tell me what's wrong?
It works when you click on the proper column and fails when you click on another, doesn't it? You have fixed logic (parsing the duration number) applied to a variable column (depending on the exact column the user clicked). Access the column with a fixed number, don't check for the selected column index.
You are trying to parse a String which does not translate into a number. It looks like the problem is you are working off of whatever the user has selected. You either need to restrict the data you are processing to be from certain columns in your table, or validate the data before trying to process it.

Parsing a List<List<String>> in Android?

I'm developing a custom Adsense report tool using Google Java Client Library for Android. I've successfully authenticated and can make API calls to the server. but now when I receive the response, I don't know how to parse it and correctly show the result to user.
According to the javaDocs, AdsenseReportsGenerateResponse.getRows() generates a List> But I'm kinda lost how to properly parse it to get:
-Today's earnings
-Yesterday's earnings
-Last 7 days
-Last month
-From the beginning of time
Here's part of my code related to the question
Reports.Generate request = adsense.reports().generate(startDate, endDate);
request.setMetric(Arrays.asList("PAGE_VIEWS", "AD_REQUESTS", "AD_REQUESTS_COVERAGE", "CLICKS",
"AD_REQUESTS_CTR", "COST_PER_CLICK", "AD_REQUESTS_RPM", "EARNINGS"));
request.setDimension(Arrays.asList("DATE", "WEEK", "MONTH"));
request.setSort(Arrays.asList("+DATE"));
AdsenseReportsGenerateResponse response = request.execute();
//TODO: Here be dragons
response.getRows();
Edit: Here is the javaDoc which mentions the getRow()
Hmm it seems nobody on this site can help?!
You should find our sample code useful: http://code.google.com/p/google-api-java-client/wiki/APIs#AdSense_Management_API
Namely, this is the file you're interested in: http://code.google.com/p/google-api-java-client/source/browse/adsense-cmdline-sample/src/main/java/com/google/api/services/samples/adsense/cmdline/GenerateReport.java?repo=samples
Here's a snippet of code to print the output. Mind you, this is for a command line application, but should be easily adaptable:
if ((response.getRows() != null) && !response.getRows().isEmpty()) {
// Display headers.
for (AdsenseReportsGenerateResponseHeaders header : response.getHeaders()) {
System.out.printf("%25s", header.getName());
}
System.out.println();
// Display results.
for (List<String> row : response.getRows()) {
for (String column : row) {
System.out.printf("%25s", column);
}
System.out.println();
}
System.out.println();
} else {
System.out.println("No rows returned.");
}
As for getting the data for different periods of time, you should probably be running different reports, not cramming it all into one, as that would take different start dates and end dates. Here's how it works:
Today's earnings: set the start and end dates to today, set the dimension list to just DATE
Yesterday's earnings: set the start and end date to yesterday, set the dimension list to just DATE
Last 7 days: if you want data per day, then you set the start date to 7 days ago, the end date to today, and the dimension list to just DATE. If you want to aggregate the stats, you may need to calculate this yourself, as WEEK and MONTH refer to a calendar week and month, not the last 7 days.
Last month: start date 1st of last month, end date last day of the month, dimension MONTH.
All time: how do you want this aggregated? Per month? Then set the start date to, say, 1980-1-1, end date to today and dimension to MONTH.
This blog post should help with understanding reporting concepts a bit better: http://adsenseapi.blogspot.com/2011/11/adsense-management-api-diving-into.html
Let me know if you need help with anything else!
Its not a List<List> as far as I understand the api. Try this:
String[][] array = response.getRows();
for (int i = 0; i < array.getSize(); i++){
String dimension = array[i][0];
String metric = array[i][1];
//Do what you want with them
}
I am writing this because the API says it has a list of dimensions with one value for the string and one for the metric, as far as I understand.
If you expect several cells on each row (Which I believe the API doesn't work that way), you need to add another for inside and get the size of the current list probably with something like array[i].getSize()
Post back if it doesn't help you.
Edit: I see now. Try this:
List list = response.getRows();
for (int i = 0; i < list.size(); i++){
List<String> list2 = list.get(i);
for (int j = 0; j < list2.size(); j++){
String value = list2.get(j);
//Do what you want
}
}

Categories

Resources