Hello. I want to create a function that generates ascending numbers.
For example, if today's date is June 21st, 2013 then the numbers will be 130621001.
The last three digits are ascending numbers, and it'll reset back to 001 on each date.
I can figure out on how to make the date digits, but I'm stuck with those last three digits.
Thank you in advance.
try this, good luck
public static String NextNumber(String currentNumber) {
//assume yymmddnnn
String sDateNum = currentNumber.substring(0, 6);
String sCurrentNum = currentNumber.substring(6,9);
int i = Integer.valueOf("1" + sCurrentNum);
i++;
return sDateNum + String.valueOf(i).substring(1, 4);
}
System.out.println(NextNumber("130621001"));
The real question is how you know what your previous answer was.
today = myDateFormatter(System.currentTimeMillis());
if (today.equals(oldDay)) count++;
else count == 0;
oldDay = today;
If this is a long running process, oldDay and count can be simple fields in your class. If the process exits and restarts, you will need to get your old answers from somewhere and set them to the largest value.
Related
public void askForDate(Scanner in) {
System.out.println("Please enter the date that the vehicle entered the car park in this format dd/mm/yyyy :");
String enteredDate = in.nextLine();
//This array will hold the 3 elements of which the date is made up of, day, month and year, and this method returns it.
String[] dateEnteredSplit = enteredDate.split("/");
//I am using the split method to seperate each number, which returns an array, so I am assigning that array to the dateEnteredSplit array.
//dateEnteredSplit = enteredDate.split("/");
//So now the first element holds the day, second the month, and the third element holds the year.
//System.out.println(Arrays.toString(dateEnteredSplit));
//Assigning each element and converting them to integers.
int day = Integer.parseInt(dateEnteredSplit[0]);
int month = Integer.parseInt(dateEnteredSplit[1]);
int year = Integer.parseInt(dateEnteredSplit[2]);
**System.out.println("day: " + day + " month: " + month + " year: " + year);**
//The loop will be entered if any of the values are wrong. which will use recursion to call this method again for a chance to enter the date again.
while (!(day >= 1 && day <= 31) || !(month >= 1 && month <= 12) || !(year > 1000 && year < 5000)) {
**System.out.println("day: " + day + " month: " + month + " year: " + year);**
//Im calling these methods to inform which one specifially was wrong so they know what they need to change.
this.setDay(day);
this.setMonth(month);
this.setYear(year);
dateEnteredSplit[0] = "0";
askForDate(in);
}
//I then assign any correct value into the object attribute because the while loop is either finished or not entered at all.
//No need to use setDay etc. here because the checks have been done above in the while loop.
this.day = day;
this.month = month;
this.year = year;
}
Ok that is a method in a class. It asks for input in the format dd/mm/yyyy
If the first time I input 12/1/1996 it works, but if I enter a wrong date for example like this first, 123/123/123 and the enter a correct date for example 12/1/1996, it still enters the loop.
After debugging, the first line that is bold, the values are different from the second line that is bold, its like the values are changing by their own.
What is the problem here? I have been trying to find out in the past 1 hour.
Thanks in advance!
The problem very likely is in the way you are trying to combine recursive and iterative approach to update values (there is a while loop, that call the function recursively, which may also trigger while loop in next level of call and the previous one will continue calling itself recursively and you will end up with just mess)
There is no real reason to do that recursively, I would do iterative only approach, something like this:
public void askForDate(Scanner in) {
System.out.println("Please enter the date that the vehicle entered the car park in this format dd/mm/yyyy :");
int day, month, year;
do { // We use do-while to get the first read without condition, although setting date to invalid value (like day = 0) and then running standard while loop will work just as fine
String[] dateEnteredSplit = in.nextLine().split("/");
//Assigning each element and converting them to integers.
day = Integer.parseInt(dateEnteredSplit[0]);
month = Integer.parseInt(dateEnteredSplit[1]);
year = Integer.parseInt(dateEnteredSplit[2]);
} while (!(day >= 1 && day <= 31) || !(month >= 1 && month <= 12) || !(year > 1000 && year < 5000));
// Now day month and year variables are set correctly and we can do stuff with it
}
If you insist or recursive approach, the correct way would be to call the function just once:
public void askForDate(Scanner in) {
System.out.println("Please enter the date that the vehicle entered the car park in this format dd/mm/yyyy :");
int day, month, year;
String[] dateEnteredSplit = in.nextLine().split("/");
//Assigning each element and converting them to integers.
day = Integer.parseInt(dateEnteredSplit[0]);
month = Integer.parseInt(dateEnteredSplit[1]);
year = Integer.parseInt(dateEnteredSplit[2]);
if (!(day >= 1 && day <= 31) || !(month >= 1 && month <= 12) || !(year > 1000 && year < 5000)) askForDate(in);
// You need to save day/month/year variables to other than local scope (like this.day = day)
// Otherwise it would just somewhere in recursion stack and you wouldn't be able to use it
}
Just to be complete, keep in mind that date string could be wrong in other way that just number out of range. What if user types 1. 2. 3456 or a/b/c or not even something very different like Hello
At your snippet of code would crash (either throw NumberFormatException when trying to parse non-integer or ArrayIndexOutOfBoundsException when accessing dateEnteredSplit array at element that doesnt exists (there are no '/' in 'Hello'))
Here is what happens. Wrong values on a first while loop iteration make a call to askForDate possible. You receive a second prompt and provide correct input. The second call of askForDate ends as expected. The execution returns again to a while loop, where you still have the first wrongly set values and the process starts again.
If you really do want to use recursion here, you should return a value from your function (dates or boolean flag) and check it in a while loop condition.
I was in a job interview and got this question: " Write a function that gets 2 strings s,t that represents 2 hours ( in format HH: MM: SS ). It's known that s is earlier than t.
The function needs to calculate how many hours between the two given hours contains at most 2 digits.
For example- s- 10:59:00, t- 11:00:59 -
Answer- 11:00:00, 11:00:01,11:00:10, 11:00:11.
I tried to do while loops and got really stuck. Unfortunately, I didn't pass the interview.
How can I go over all the hours (every second is a new time) between 2 given hours in java as explained above? Thanks a lot
Java 8 allows you to use LocalTime.
LocalTime time1 = LocalTime.parse(t1);
LocalTime time2 = LocalTime.parse(t2);
The logic would require you to count the amount of different digits in a LocalTime, something like
boolean isWinner(LocalTime current) {
String onlyDigits = DateTimeFormatter.ofPattern("HHmmss").format(current);
Set<Character> set = new HashSet<>();
for (int index = 0; index < onlyDigits.length(); index++) {
set.add(onlyDigits.charAt(index));
}
return set.size() <= 2;
}
You can loop between the times like this
int count = 0;
for (LocalTime current = time1; current.isBefore(time2); current = current.plusSeconds(1)) {
if (isWinner(current)) {
count++;
}
}
That's it.
The question is really more geared towards getting a feel of how you'd approach the problem, and if you know about LocalTime API etc.
this is my first question here ever, and I would appreciate if you can help me.
Since the code I have is way too large to post here, I'll try to describe what my problem is in short.
So, I have made TimeSeries array within my class and array list from where I get values for time series:
private TimeSeries[] seriesArray = new TimeSeries[10];
ArrayList<TempClass> valuesFromArrayList = new ArrayList<>();
I need to make TimeSeries array, because I want to be able to show multiple timeseries graphs. Using only one TimeSeries and addOrUpdate method isn't what I want because then values get mixed when I create more graphs. So, I add values like this:
for(int i = 0; i < valuesFromArrayList.size(); i++)
{
TempClass obj = (TempClass) valuesFromArrayList.get(i);
int timeStamp = obj.getTimeStamp();
int hrsDiff;
int minsDiff;
int secsDiff;
hrsDiff = timeStamp / 3600;
timeStamp = timeStamp - hrsDiff * 3600;
minsDiff = timeStamp / 60;
timeStamp = timeStamp - minsDiff * 60;
secsDiff = timeStamp;
seriesArray[Integer.parseInt(comboBoxValue) - 1].add(new Second(secsDiff, minsDiff, hrsDiff, day, month, year), Math.abs(obj.getValue()));
}
What this part of code does is that it reads values and timestamps from ArrayList I created. There is comboBox where user can choose which timeSeries array index will be in graph. So, if user chooses value 9 from comboBox, timeSeries from index 8 will be chosen and plotted on graph. TimeStamp is simply number of seconds that passed since 00:00:00 at day when values were taken.
TempClass is defined as:
class TempClass
{
private int timeStamp;
private double value;
public TempClass(int a, double b)
{
timeStamp = a;
value = b;
}
public int getTimeStamp()
{
return timeStamp;
}
public double getValue()
{
return value;
}
public void setValue(double val)
{
value = val;
}
}
The problem I have is that when I try to make second (2nd) graph, that is another index of TimeSeries array, I get message:
You are attempting to add an observation for the time period Thu Apr 30 00:00:00 CEST 2015 but the series already contains an observation for that time period. Duplicates are not permitted. Try using the addOrUpdate() method.
I don't want to use addOrUpdate method, I need add method. Values in ArrayList I use to put values into timeSeries are fine, I am 300% sure. I already checked input from comboBox value and it gives correct values.
I have no explanation other that for some reason, even if array index is changed, data I want to write into the series goes to the old series (that is, to the series at the old index). In other words, it seems like even if I change index of array, it keeps writing into the old array index!
It's like equivalent to this (I know this sounds crazy but that is basically what I am getting):
int[] array = new int[5];
array[0] = 1;
array[1] = 2;
System.out.println(array[0]);
And the output I get is
2
This is something I have never heard of before, and I have code similar to this I wrote here in two other places, and in that two places it goes just fine, but in this third place I keep getting that exception.
Is this some kind of bug in JVM?
Does somebody know what this could be?
I don't know too much about TimeSeries, but after skimming the docs about it it says:
"The time series will ensure that (a) all data items have the same
type of period (for example, Day) and (b) that each period appears at
most one time in the series."
Link to Docs
I'm guessing the error is pretty straight forward or a misuse of TimeSeries. It looks like you are simply adding a duplicate date and that the constraints of TimeSeries don't allow that.
You may wish to consider writing a custom class that has the functionality you want. Yet again, I don't know much about TimeSeries, but I hope this helped a little.
Your for loop will always overwrite the value with an index of 0 on seriesArray.
What I mean is, the first time it will write to [0]
The second it will write to [0] then [1]
Is this intended?
I have not looked at the docs too much, but the message says 'the series already contains an observation for that time period.' I think that loop is not doing what you want it to do.
I have homework where I have to write a small program that asks for a number and returns the month assigned to that number.
So far I have written two different classes, one to prompt the user for int, and the other with the arrays of month. Now my problem is to pass over the months to the main class when the user enters a number.
So far for the main class I have this and I have no idea on how to proceed...
I get:
java:17: error: array required, but Date found System.out.println(monthName[index]);
I tried to be as detailed as possible.
import java.util.Scanner;
public class Driver {
public static void main(String[] args)
{
Utility input = new Utility();
final int MONTH_NAMES = 12;
int[] month = new int[MONTH_NAMES];
Date monthName = new Date();
{
System.out.println(input.queryForInt("Enter the number for a month ")) ;
}
for (int index = 0; index < 12; index++)
System.out.println(monthName[index]);
}
}
Your System.out line is not referencing the array you named month.
I don't think you intended to use Date monthName here
System.out.println(monthName[index]);
Judging by the number of indexes your for loop is counting, it looks like you wanted to use int[] month.
System.out.println(month[index]);
mouthName is a Date object, not an array. Also, why use a for loop to print out a whole year's mouth?
I think it can change the last for loop to System.out.printLn(mouthName.getMouth()) if the input.queryForIntmethod can successfully pass the int mouth to the mouthName object.
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
}
}