Sum old variable with new variable - java

I have an Adapter that points to items that have a "Time" attribute.
If the user taps a button on one item and on another I'd need both Time values to be summed. I can't achieve this.
I've tried stuff like time += time, separate those values etc
This was the last thing I was trying. Yeah it makes no sense but idk, nothing had worked.
[...]
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GetTime(gameItem.getTime());
}
});
}
private int GetTime(int timeplayed) {
time += timeplayed;
return time;
}
Which should have been like at the start there is an empty variable time.
timeplayed is added to it and is returned as time.
So eveytime you tap the button the timeplayed gets added and returned as time
Actually tho, instead of summing the old variable with the new one it either does just a 0 + number or it sums the new variable with itself...

From what you said it sounds to me that the field value is being altered or actually not initialized at all before you get to actually do your mathematical operations on it. So the answer to your question is simple: make sure the value of the field is not changed before your code reaches the private int GetTime(int timeplayed) method.
In any case your code absolutely should work as the syntax of the operation is correct. time += timeplayed is equivalent to time = time + timeplayed. I can't see the rest of your code so I can't really say whats going on underneath the hood but if you are willing to share the rest of your code, pretty much anywhere the time variable is being altered (including the place where it's being actually initialized) I could help you out further.
But first you need to make sure the variable has an expected value (not the same as timeplayed and not 0). You can do this through debugging either with using breakpoints or logging the value in console before the operation gets executed.
Hope this helps, let me know how it goes.

Related

How can I print a return value from a function in Java?

I am writing a program for calculating pay for overtime hours and non-overtime hours. This is for my Java course, so the requirements are that I must have two classes and three functions. The first class does not have a main and contains three functions. It's basically where the calculation is done.The second class is for I/O, where you input your values through the Scanner and display the result.
I think I am almost done, however, I cannot get my total pay amount to return in my I/O class, it comes out as 0.0. How can I get it to properly return my function getPayAmount() value?
Here is the image of my first class, the three functions: constructor, payCalculation, and getPayAmount()
Here is the image of my second class, where the I/O is done.
Again, I'd like to know how I can return the value from my getPayAmount() function to print at my last sys.out statement.
Thanks so much in advance for your help, I'm so anxious to be done with this!
try creating paycheck calculation after getting the input. move line 11 to 25
PayCheckCalculation myPay= new PayCheckCalculation (hours,rate);
myPay.payCalculation(rate,hours);
When you are creating the object mypay, the parameters are rate and hours have value as 0. Instead you want to instantiante the object with the values you get as input and you should get the right answer. Also you should use this in your class methods to refer to current object.
You did not call the method paycalculation method in your code as well.
In line 11 of your main function, you're creating the mPay object with (0,0) as initial values, you could initiate the object, you get the required information from the console or user, then the variables in the object will have updated values in them.
You could create or initiate the object after line 25 so that, you will have all the required data to calculate the payroll information from the user.
To understand an error, always check the flow of your code, this way you can find most of your errors.

Count elements in array

I am trying to count an element in an array of objects.
long number = Stream.of(jobTitle).count();
System.out.println("There are " + number + " employees.");
What happens is that it will print out the message as many times as many employees have the same job title. Yet "number" stays always 1.
Any guiding would be much appreciated.
long number = Stream.of(jobTitle).count();
Counts the elements in a stream that contains one element.
It is not surprising that this operation always ends up with the exact same result.
Your code is equivalent to:
List<Whatever> titels = new ArrayList<>();
titels.put(oneEntry);
... print titels.size()
Long story short: that statement is nonsensical. What you probably meant was:
if (arbetstitel.equalsIgnoreCase(jobCount)){
g++;
or something alikw. Of course g is a rather bad name for a counter.
But the real answer here is: step back. Think what the problem is you intend to solve, and what the elements are you need to look at. The code you are showing here is simply not making (much) sense. I can't tell you how to fix it, because, as said: it is not clear what you try to achieve here.
A streamish way of counting:
long usersWithMatchingTitle = Arrays.stream(employees).filter(e -> e.getJobTitle().equalsIgnoreCase(jobTitleFromUser)).count();
Meaning: instead of manually iterating your array, you can turn the whole array into a stream, and then filter/count whatever you want to.
Please note: your code seems to only care about the first 30 elements in that array. If that is really what you want, you will need ...stream(employees).limit(30)...
You need to change the stream of command to define a proper Predicate for filter option.
Stream.of(employees).filter(e -> e.getJobTitle().equals(jobTitle)).count();

How do I stop certain code from running?

I have a class that "bans" a player, but I don't want that player to be banned if his name is within a string array. I could loop through the length of the array and use booleans, but there has to be an easier way? I saw something that said just put if a condition is met, put return; and it'll stop all code running below that if statement.
Edit: Thanks for all the help! You were all helpful, even if you're one of the people that downvoted this, which is 4 people at least.
You could make a method that checks if the player is in the array of Strings and yes if you use return in a void method the method will just end.
For example
public void returnUsage(int n)
{
if(n==1)
{
return;
}
System.out.println("n doesn't equal 1.");
}
But it would probably be best to use an if and else to skip the code you don't want to run if the condition is not met. http://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html
An array is the wrong data structure for this task. Add the players to a Set<> allowedPlayers = new HashSet<String>() then use if(allowedPlayers.contains(name)) return; to conditionally exit the method based on whether the name of the player is in the set. The set will remain fast when the number of names gets large. With an array scanning the array will be slow when the array is big.

Impose order in Jsprit with HardActivityConstraint

In a scenario of re-solving a previously solved problem (with some new data, of course), it's typically impossible to re-assign a vehicle's very-first assignment once it was given. The driver is already on its way, and any new solution has to take into account that:
the job must remain his (can't be assigned to another vehicle)
the activity that's been assigned to him as the very-first, must remain so in future solutions
For the sake of simplicity, I'm using a single vehicle scenario, and only trying to impose the second bullet (i.e. ensure that a certain activity will be the first in the solution).
This is how I defined the constraint:
new HardActivityConstraint()
{
#Override
public ConstraintsStatus fulfilled(JobInsertionContext iFacts, TourActivity prevAct, TourActivity newAct, TourActivity nextAct,
double prevActDepTime)
{
String locationId = newAct.getLocation().getId();
// we want to make sure that any solution will have "C1" as its first activity
boolean activityShouldBeFirst = locationId.equals("C1");
boolean attemptingToInsertFirst = (prevAct instanceof Start);
if (activityShouldBeFirst && !attemptingToInsertFirst)
return ConstraintsStatus.NOT_FULFILLED_BREAK;
if (!activityShouldBeFirst && attemptingToInsertFirst)
return ConstraintsStatus.NOT_FULFILLED;
return ConstraintsStatus.FULFILLED;
}
}
This is how I build the algorithm:
VehicleRoutingAlgorithmBuilder vraBuilder;
vraBuilder = new VehicleRoutingAlgorithmBuilder(vrpProblem, "schrimpf.xml");
vraBuilder.addCoreConstraints();
vraBuilder.addDefaultCostCalculators();
StateManager stateManager = new StateManager(vrpProblem);
ConstraintManager constraintManager = new ConstraintManager(vrpProblem, stateManager);
constraintManager.addConstraint(new HardActivityConstraint() { ... }, Priority.HIGH);
vraBuilder.setStateAndConstraintManager(stateManager, constraintManager);
VehicleRoutingAlgorithm algorithm = vraBuilder.build();
The results are not good. I'm only getting solutions with a single job assigned (the one with the required activity). In debug it's clear that the job insertion iterations consider many viable options that appear to solve the problem entirely, but at the bottom line, the best solution returned by the algorithm doesn't include the other jobs.
UPDATE: even more surprising, is that when I use the constraint in scenarios with over 5 vehicles, it works fine (worst results are with 1 vehicle).
I'll gladly attach more information if needed.
Thanks
Zach
First, you can use initial routes to ensure that certain jobs need to be assigned to specific vehicles right from the beginning (see example).
Second, to ensure that no activity will be inserted between start and your initial job(location) (e.g. "C1" in your example), you need to prohibit it the way you defined your HardActConstraint, just modify it so that a newAct can never be between prevAct=Start and nextAct=act(C1).
Third, with regards to your update, just have in mind that the essence of the algorithm is to ruin part of the solution (remove a number of jobs) and recreate the solution again (insert the unassigned jobs). Currently, the schrimpf algorithm ruins a number of jobs relative to the total number of jobs, i.e. noJobs = 0.5 * totalNoJobs for the random ruin and 0.3 * totalNoJobs for the radial ruin. If your problem is very small, the share of jobs to be removed might not sufficiant. This is going to change with next release, where you can use an algorithm out of the box which defines an absolute minimum of jobs that need to be removed. For the time being, modify the shares in your algorithmConfig.xml.

Entering both if AND else statement?

So I've got this code (updated for solution).
#Override
public View getView(int position, View convertView, ViewGroup parent) {
...
final Direction d = directions.get(position);
if (d != null) {
TextView direction = (TextView) row.getTag(R.id.directionTextView);
TextView departure1 = (TextView) row.getTag(R.id.departure1);
TextView departure2 = (TextView) row.getTag(R.id.departure2);
TextView departure3 = (TextView) row.getTag(R.id.departure3);
direction.setText(d.getName());
if (d.getTimeStamps().size() == 0) {
departure1.setText(R.string.nodepartures);
departure1.setTextColor(R.color.grey);
} else {
for (int i = 0; i < d.getTimeStamps().size(); i++) {
switch (i) {
case 0:
departure1.setText(d.getTimeStamps().get(i));
break;
case 1:
departure2.setText(d.getTimeStamps().get(i));
break;
case 2:
departure3.setText(d.getTimeStamps().get(i));
break;
default:
break;
}
}
}
}
return row;
}
}
The problem I was having was that one of the TextViews would turn grey when it wasn't supposed to. I tried fixing it by always setting the text to black again, but that turned every single one of them grey. Until I tried:
setTextColor(context.getResources().getColor(R.color.black));
instead of just
setTextColor(R.color.black);
Don't know why the latter works when setting text grey, but there it is. I guess I'm just a little retarded. :)
What you think is happening simply cannot happen (*, **). What you need to do is prove to yourself that it is not happening.
I'd do this by adding some traceprints to the code. Put one before the if statement, one at the starts of the "then" and "else" clauses, and one after the if statement. Then run it. I expect that this will reveal that the if statement is actually being run twice, and running the "then" clause the first time and the "else" clause the second time.
(* In theory, it might happen if there was a serious bug in the emulator. But you should only consider that as a possibility if you have irrefutable evidence.)
(** Another possibility is that there might be a significant difference between the sample code above and the actual code you are testing. It happens ...)
AsLanFromNarnia is on the right track. ListView recycles its child views. You can never assume that convertView is in any sort of default state for its type. Set every relevant field every time getView is called. In your case it means setting the text color when you set the text.
There is another way to handle cases like this where you want to have heterogenous lists: use view types. Your adapter can return the number of types you have for getViewTypeCount and then report the type of each item from getItemViewType. If you do this, you will always get a convertView passed into your getView method of the proper type, alleviating the need to change otherwise static layout each time.
Hmm... I can't see how that would happen. Are you sure your brackets are in the right place? Does it still occur if you switch the statement around?
I agree with Aircule! This code is pretty nutty! How about this?
if(d.getTimeStamps().isEmpty())
{
departure1.setText(R.string.nodepartures);
departure1.setTextColor(R.color.grey);
}
else
{
departure1.setText(d.getTimeStamps().get(0));
departure2.setText(d.getTimeStamps().get(1));
departure3.setText(d.getTimeStamps().get(2));
}
It should do the exact same thing an it's a lot less complicated. Also, let's say you run this code once and the list is empty, so you set the color of departure1 to gray and run it again. This time you get data and fill in the items, but you never change the color of departure1, so it will stay gray. Similarly, if you take that scenario the other way around, you don't empty the TextViews when the list is empty. Another tip, if there are only ever going to be three items (or any small fixed number of items) then you're probably better off just using a normal layout instead of a list. That way you won't have to go through making a custom adapter, you can just call the items by name.
Have you set a default color or styling in your layout XML file that is loaded by LayoutInflator?
I believe it's turning gray because at some point in your program the method is being called with 0 timestamps.
It only has to happen once for it to set the departure1.textColor attribute, then it will persist until changed back.
You mentioned you tried setting it to black in the else statement but it turned everything gray. This doesn't make sense at all. Try adding the command to turn text to black at each case statement, so:
case 0:
departure1.setTextColor(R.color.black);
departure1.setText(d.getTimeStamps().get(i));
break;
case 1:
departure2.setTextColor(R.color.black);
departure2.setText(d.getTimeStamps().get(i));
break;
case 2:
departure3.setTextColor(R.color.black);
departure3.setText(d.getTimeStamps().get(i));
break;
Based on what you describe we can only give hints at best.
Are you sure you recompiled all your code? I have seen debugging yield funny results because part of code was not in synch with the bytecode beng debugged
Is this an event based system? Could it be that your code is called twice, once with teh empty list followed directly by the list with 1 entry after that entry is added to the list?
As code improvement I would do the following to refactor the switch (assumption here is the control type is Text which is probably wrong but easily fixed):
if (d.getTimeStamps().isEmpty()) {
departure1.setText(R.string.nodepartures);
departure1.setTextColor(R.color.grey);
} else {
Text[] fields = new Text[] { departure1, departure2, departure3 };
for (int i = 0; i < fields.length && i < d.getTimeStamps().size(); i++) {
fields[i].setText(d.getTimeStamps().get(i));
fields[i].setTextColor(R.color.black);
}
}
update
Seeing that you do not set the color for departure values, I think you assume that the lines are freshly created when this code runs. If that assumption is incorrect, your situation might be that a line that previously held a 'no departure' line, now gets re-used for a departure line therefore inheriting the grey color.

Categories