Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm trying to add all elements in my ArrayList but it seems quite a challenge. Tried different methods and functions but none of them worked. Here is my code:
for (Kids ki : GroupOfKids) {
try {
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
String currentDate= dateFormat.format(date);
Date datum;
datum = dateFormat.parse(currentDate);
Date bornDate;
bornDate= ki.getbornDate();
int days = daysBetween(bornDate, datum);
//code above works fine..from here it's getting confusing
List<Integer> allKids;
allKids= new ArrayList<>();
allKids.add(days);
int total;
total = allKids.stream().mapToInt(Integer::intValue).sum();
System.out.print(total);
} catch (Exception e) {
e.printStackTrace();
}
}
I'm calculating how old are the "Kids" in days. I get an int and put the results in the ArrayList. I'm unable to get one result. I either get for each kid alone how old he/she is or I get both results if there are 2 for example stacked.
Example:
Kid 1 is 1234 days old
Kid 2 is 3422 days old
Result: 12343422
I expect 1234 + 3422 = 4656.
If there are more entries, then the sum of all together.
Can someone tell me where I'm making a mistake?
The first thing I see is using the old java.util.Date instead of the new java.time.LocalDate; then use the Period class to determine the number of days (probably could have modified your daysBetween if you had posted it). Like,
private static int getDaysOld(Date d) {
return Period.between(d.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(),
LocalDate.now()).getDays();
}
Then your stream should be used to map each Kids to their age and sum; like
int total = allKids.stream().mapToInt(k -> getDaysOld(k.getbornDate())).sum();
Let's say that you are doing sum in a wrong place.
You should define and initialize your list before the loop and do your summation after the loop ends.
List<Integer> allKids;
allKids = new ArrayList<>();
for( ... ) {
.
.
.
allKids.add(days);
.
.
.
}
int total;
total = allKids.stream().mapToInt(Integer::intValue).sum();
System.out.print(total);
Related
I'm comparing an arrayList to itself using foreach.
I have an arrayList containing tips for waiters, each object has a date "dd-MM-yyy" and an amount (double),
Now i want to add all transactions for the same day, so i get a total for the day that can be divided between the waiters.
Without duplicates.
I've looked all over especially here, but I can't seem to find a solution.
I really hope you guys can help, I know it's a bit embarrassing, seeing as the problem being so simple, but I've been working on it for a couple of days now and I'm stuck.
I had a longer algorithm but it wouldn't work and I couldn't find any solutions online, so i broke it all down to it's most basic components and checked for each step and pretty early on this problem occured:
I'm using a local arrayList to make sure that I'm not comparing the same days to eachother over and over again.
The if(!alreadyMade.contains(tips1.getTime()) followed by alreadyMade.add(tips1.getTime()) seems to be producing duplicates, which in my mind makes no sense.
All I want is to add all the transactions for the same day from the same arrayList.
public void dist(){
double day = 0;
List<String> alreadyMade = new ArrayList<>();
for (Tips tips : data.getTips()) {
for (Tips tips1 : data.getTips()) {
if(tips.getTime().equals(tips1.getTime())) {
if (!alreadyMade.contains(tips1.getTime())){
alreadyMade.add(tips1.getTime());
day += tips.getTips();
}
}
}
System.out.println(day);
day = 0;
}
}
I wanted the print to be for a single day, but it is printing a lot of numbers that doesn't make sense
I think you're trying to do something like this:
Map<String,Double> alreadyMade = new HashMap<>();
for (Tips tips : new ArrayList<Tips>()) {
// If this time doesn't exist in the map then add it to the map with the
// value tips.getTips(). If this time does exist in the map then add
// the value of tips.getTips() to the value that is already in the map.
alreadyMade.merge(tips.getTime(), tips.getTips(), (Double a, Double b) -> a + b);
}
// go through each map entry. The keys are the times and the values are the tip totals for that time.
for (Map.Entry<String, Double> entry : alreadyMade.entrySet()) {
System.out.println("Time: " + entry.getKey() + " Tips: " + entry.getValue());
}
Note: I couldn't test this because I'm running Java 7 and this map function isn't available until java 8.
In Java 8+ you can use the stream API to group by the time:
Map<Date, Integer> alreadyMade = data.getTips().stream()
.collect(groupingBy(Tip::getTime, summingInt(Tip::getTips)));
I would do it like the following:
This is your Tip class(I think)
public class Tip{
Date date;
float tip;
public Tip(Date date, float tip){
this.date = date;
this.tip = tip;
}
}
And this is the ("Algorithm")
//To Format the Dates
SimpleDateFormat ft = new SimpleDateFormat("dd-MM-yyyy");
//Input
ArrayList<Tip> tips = new ArrayList<Tip>();
//Just some Data for testing
tips.add(new Tip(ft.parse("11-04-2019"), 2.40F));
tips.add(new Tip(ft.parse("25-04-2019"), 3.30F));
tips.add(new Tip(ft.parse("25-04-2019"), 0.90F));
//Output
ArrayList<Date> dates = new ArrayList<Date>();
ArrayList<Float> sum = new ArrayList<Float>();
for(Tip tip : tips){ //Go through each Tip
int match = dates.indexOf(tip.date); //Look if the date is already in the array (if not -> -1)
if(match == -1){ //If not add it
dates.add(tip.date);
sum.add(tip.tip);
}else { //If yes set it
sum.set(match, sum.get(match) + tip.tip);
}
}
//Output to console
for(int i = 0; i < dates.size(); i++){
System.out.println(ft.format(dates.get(i)).toString() + " " + String.valueOf(sum.get(i)));
}
There is also a solution with maps or pairs but I never worked with them (not a professional coder). Also make sure to try-catch the ParseException. I Hope thats what you meant. :)
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.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
(At time of posting, I do not have access to code, will add later)
I have an array of Employee objects, which hold a name, availability, and preferred hours. And I sort the objects by Alphabetical order, according to the employees name.
When the program starts, it checks the files, and if they are empty, it asks you how many employees, and then you proceed to fill in the data. And it sorts properly A-Z.
This issue comes that when I try to add a new employee, after resizing the array, it adds it to the end, even though the sort completes.
So it sorts the first time, but not again after re running the program. I will post the code when I get home, but wanted to see if anyone had any answers in the mean time. Thank you
static void employeeSort(Employee[] emply, int size)
{
int i;
Employee temp;
boolean flag = true;
while(flag)
{
flag = false;
for(i = 0; i < size; i++)
{
if (emply[i].getName().compareTo(emply[i+1].getName())>0)
{
System.out.println(emply[i].getName());
temp = emply[i];
emply[i] = emply[i+1];
emply[i+1] = temp;
flag = true;
}
}
}
}
On the first run through, it sorts everything correctly, but once the array is read from a file, the program terminates in the sort. I tried implementing the priority queue, but i needed to make the Class comparable, and its already implemented Serializable.
public class Employee implements Serializable
{
int prefHours;
String name;
String avail;
Employee( String nam, int hours, String aval )
{
name = nam;
prefHours = hours;
avail = aval;
}
void prnEmpl()
{
System.out.print("Name: " + name);
System.out.println();
System.out.print("Prefered hours: " + prefHours);
System.out.println();
System.out.print("Availability: " + avail);
System.out.println();
}
String getName()
{
return name;
}
String getAvail()
{
return avail;
}
}
Without your code it is hard to figure out what's the problem. As far as I understand I think you should use java.util.PriorityQueue instead of Array.
These questions might have really simple answers but in this code
public void setupYears()
{
ArrayList<String> years_tmp = new ArrayList<String>();
for(int years = Calendar.getInstance().get(Calendar.YEAR)-90 ; years<=Calendar.getInstance().get(Calendar.YEAR);years++)
{
years_tmp.add("Year"+years+"");
}
Y = new JComboBox(years_tmp.toArray());
Y.setLocation(404,310);
Y.setSize(250,25);
Y.setEditable(false );
firstPanel.add(Y);
}
How do I firstly reverse the years so the first year would be the current year and the last year would be 90 years ago instead of vice versa?
Also how would I put the "Year" as the first object in the JComboBox instead of "Yearxxxx"?
"xxxx" being whatever year is displayed in the JComboBox
To solve the ordering problem:
for(int years = Calendar.getInstance().get(Calendar.YEAR) ; years>=Calendar.getInstance().get(Calendar.YEAR)-90;years--)
And to put "Year" in the first box, simply add the line
years_tmp.add("Year");
before your for loop.
Hope this helps.
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.