How to get the remaining in java - java

I have a java program that will run every 15th and last day of the month, i have sample that has 2 different type of amount.
this type of amount is come from the query and its already sort by sysdate, this is the result of the query:
130
500
while running the program it will automatically deduct from the first amount and the remaining will go to the second amount.
this is first amount 125.
and this is the second amount 100.
how do i do that? it really appreciated your help.
//this is the query to get the 130,500.
String getAdvanceEmployee = "SELECT AMOUNT FROM CFV_CHARGES WHERE EMP_NO = '40000124' AND TO_DATE(DUE_DATE) = '30-JUN-19' AND IS_ADVANCE = '1'";
ResultSet result1 = stmt.executeQuery(getAdvanceEmployee);
while(result1.next()){
String amount = result1.getString("AMOUNT");
//the output 130,150
//this is the query to get the 125.
String getAdvancePayment = "SELECT AMOUNT FROM CFV_CHARGES WHERE EMP_NO = '40000124' AND TO_DATE(DUE_DATE) = '30-JUN-19' AND ENTRY_TYPE = '1'";
ResultSet result2 = stmt1.executeQuery(getAdvancePayment);
while(result1.next()){
String amount = result1.getString("AMOUNT");
//the output will 125
//im confused the logic itself
}
}
amount from the query:
130
500
the first amount 125
the second amount 100
actual result is:
125
-125 // this negative comes from the amount of 130 the remaining -5 will go to the next amount which is this
100
-5
-95
//and the remaining last was -405.

you can calculate it this way :
public int calculatAmountOne(int firstAmount , int secondAmount){
//in your case firstAmount = 125 , secondeAmount = 130
int rest = firstAmount - secondeAmount ;
return rest
}
public int calculatAmountTwo(int firstAmount , int secondAmount){
//in your case firstAmount = 100, secondeAmount = -5
int rest = firstAmount + secondeAmount ;
return rest
}
so now that you create the two method to calculate the two different amount you can use them
int restOne = calculatAmountOne(125,130) // restOne = -5 ;
int restTwo = calculatAmountTwo(100,restOne) // restTwo = 95 ;
int lastRemaining = restTwo + 500 // lastRemaining = 595
you should later use number that you get instead of the number i put as example based on your question !

Related

Android - get index #0 , #1 , #2 of a number

how to get index #0 , #1 , #2 of a number
for example
long sec = 8541; //get 541;
long sec = 5276; //get 276;
long sec = 463; //get 463;
long sec = 95; //get 95;
and etc..
If I understood correctly you want the 3 first digits (from the right). You can get them by using modulo 1000 :
long sec = 12345;
long res = sec%1000; //res will be 345
Something like this:
int digitAtPositionOne = Integer.parseInt(Integer.toString(sec).substring(0, 1)); //change this accordingly
int digitAtPositionTwo = Integer.parseInt(Integer.toString(sec).substring(0, 2)); //change this accordingly
You can use subString from the wanted index to get only part of the number like this :
int yourNewNumber = Integer.parseInt(Integer.toString(sec).substring(start index, end index));
Note - if you won't fill your end index your new number will start at the start index given until the last index

Using objects in java (entities)

I'm new to java and I've developed a program that allows the user to enter his in- and outcome, and also to see a summary of both (second code sample).
I use text files to store the data (first sample). I'm using two text files per user, one for the income and one for the outcome.
Bonus //category
21 //amount
28/12/2015 //date
Salary
13
03/01/2016
Savings Deposit
33
03/01/2016
The following code sample sums up the in- and outcome of the user (Note: opnEsoda is a scanner):
try {
while (opnEsoda.hasNextLine());
do //I read only the lines with the amounts from textfile
{
String[] entry = new String[3];
int x =0;
for (int i = 0; i < 3; i++)
{
if (opnEksoda.hasNextLine())
{
// Trim removes leading or trailing whitespace.
entry[i] = opnEksoda.nextLine().trim();
}
}
x = Integer.parseInt(entry[1]); // converts string numbers to int
sumeksoda += x ; // addition ... Amounts of the txt file
}
while (opnEksoda.hasNextLine());
// information dialog that show the money spent and got.
JOptionPane.showMessageDialog(null,
"You got: "+sumesoda+" €",
"Your stats",
JOptionPane.INFORMATION_MESSAGE,icon);
} catch (FileNotFoundException e) {
System.out.println("COULD NOT READ FILE!!!");
}
This will print: You got 67 €
My goal is to give out the money spent this week and this month. I also want to know the amount of money spent on each category (optional). What is the best way to do that?
To calculate the income for the current month, you must analyze entry[2] (the date) inside the loop, and sum up only those values whose month is the same.
At the beginning of your program, store the current date:
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(new Date()); // store the current date
int curYear = cal.get(cal.YEAR );
int curMonth = cal.get(cal.MONTH);
Then, when reading the file, parse the date and compare the year and month:
cal.setTime(new SimpleDateFormat("dd/MM/yyyy").parse(entry[2])); // parse the date
if( cal.get(cal.YEAR)==curYear && cal.get(cal.MONTH)==curMonth ){
x = Integer.parseInt(entry[1]); // converts string numbers to int
sumeksoda += x ; // addition ... Amounts of the txt file
}
To calculate the income from each category, you must analyze entry[0] (the category). If the categories are known in advance, then simply create several distinct sum variables:
int sumeksodaSalary=0;
int sumeksodaBonus=0;
And then, inside the loop:
if("Salary".equals(entry[0])) sumeksodaSalary += x ;
if("Bonus" .equals(entry[0])) sumeksodaBonus += x ;

Give a checkbox an integer value and store in JavaDB

I am currently working on a small program that allows the ordering of items and the total cost to be stored in a JavaDB.
I have managed to successfully store integer values into the database but the cost amount for the items are not correct. It seems like when the check box is selected it is counting that as a value on top of the set value. Would anyone be able to take a look and see where I am going wrong?
Any help would be greatly appreciated!
Screenshot:
http://i.imgur.com/ad41ooG.png
OK - I think I can see your problem. Reducing the code a bit further, you have:
int fanta = 1;
int crisps = 1;
int beer = 2;
int wine = 3;
int water = 0;
...
if(btnFanta.isSelected()) fanta++;
if(btnCrisps.isSelected()) crisps++;
if(btnBeer.isSelected()) beer++;
if(btnWine.isSelected()) wine++;
if(btnWater.isSelected()) water++;
rs.updateInt("TotalCost", fanta + crisps + beer + wine + water);
So, if nothing is selected, you're adding up all the values: 1 + 1 + 2 + 3 + 0 = 7, and inserting that. If Fanta is selected, you first increment the value of fanta, making it 2, then add it to the values of all the other snacks: 2 + 1 + 2 + 3 + 0 = 8, which is what you're seeing in the database when you select Fanta.
Hopefully that makes sense, and I'm guessing that's not what you want. I'd suggest that one solution would be to add a new variable, say, totalCost, and add the values to that if the relevant checkbox is selected, so, you'd end up with something like:
int fanta = 1;
int crisps = 1;
...
int totalCost = 0;
...
if(btnFanta.isSelected()) totalCost += fanta;
if(btnCrisps.isSelected()) totalCost += crisps;
...
rs.updateInt("TotalCost", totalCost);
(In case you're not familiar with the += syntax, it's the same as saying totalCost = totalCost + fanta, i.e. you're adding fanta to whatever totalCost was previously.)

Convert Bigdecimal to Timeformat for a string

Basically, I'm using app42 to store scores for a game. However my game uses times.
For example. If I submit a score of 0:3:85 ( 0 hours, 3 seconds and 85 milliseconds)
it would be stored as a bigdecimal as 385.
When i retrieve my score I retrieve it as 385, I have no idea how I can convert it back to my time format.
Example:
At the minute i'm using a function to count how many digits the number is.
int getNumberOfDecimalPlaces(BigDecimal bigDecimal) {
String string = bigDecimal.toPlainString();
int index = string.length();
return index;
}
then to actually work it out, i'm at a loss.
Im thinking something along the lines of
private String ConvertScore(BigDecimal Score){
int Len = getNumberOfDecimalPlaces(Score);
String Convert = Score.toString();
String Finished;
if( Len == 1){
}
else if(Len == 2){
}
else if(Len == 3)
{
Finished
}
return Finished;
}
but honestly I can't even think how i'd do it.
Thanks
Correct me if I'm wrong but your API that you're using returns you the score of the game (not the, not the time. And you won't have an ability to convert it correctly. Because there could be different score.
For example, how to convert 10345?
10 hours 3 seconds and 45 milliseconds
OR
is it 103 hours 0 seconds and 45 milliseconds and so on.

Hackerrank's Minimum Average Waiting Time

Link to challenge can be found here
Problem Statement
Tieu owns a pizza restaurant and he manages it in his own way. While
in a normal restaurant, a customer is served by following the
first-come, first-served rule, Tieu simply minimizes the average
waiting time of his customers. So he gets to decide who is served
first, regardless of how sooner or later a person comes.
Different kinds of pizzas take different amounts of time to cook.
Also, once he starts cooking a pizza, he cannot cook another pizza
until the first pizza is completely cooked. Let's say we have three
customers who come at time t=0, t=1, & t=2 respectively, and the time
needed to cook their pizzas is 3, 9, & 6 respectively. If Tieu applies
first-come, first-served rule, then the waiting time of three
customers is 3, 11, & 16 respectively. The average waiting time in
this case is (3 + 11 + 16) / 3 = 10. This is not an optimized
solution. After serving the first customer at time t=3, Tieu can
choose to serve the third customer. In that case, the waiting time
will be 3, 7, & 17 respectively. Hence the average waiting time is (3
+ 7 + 17) / 3 = 9.
Help Tieu achieve the minimum average waiting time. For the sake of
simplicity, just find the integer part of the minimum average waiting
time.
Input Format
The first line contains an integer N, which is the number of
customers. In the next N lines, the ith line contains two space
separated numbers Ti and Li. Ti is the time when ith customer order a
pizza, and Li is the time required to cook that pizza. Output Format
Display the integer part of the minimum average waiting time.
Constraints
1 ≤ N ≤ 10^5
0 ≤ Ti ≤ 10^9
1 ≤ Li ≤ 10^9
Note
The waiting time is calculated as the difference between the time a
customer orders pizza (the time at which they enter the shop) and the
time she is served.
Cook does not know about the future orders.
I've been at this for several hours.
I'm pretty sure my problems has to do with the way I increment the total Wait time.
Any help would be much appreciated.
code:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
public class Solution {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
MinimumAverageWaitingTime mawt = new MinimumAverageWaitingTime();
while(n-- > 0) mawt.insert(s.nextLong(), s.nextLong());
System.out.print(mawt.calculateAverageWaitingTime());
}
}
class MinimumAverageWaitingTime {
private PriorityQueue<e_time_p_time> incomingOrders = new PriorityQueue<>(10, new Comparator<e_time_p_time>(){
//Order by the customerWaitTime ASC
#Override public int compare(e_time_p_time w, e_time_p_time w1) {
return (int) (w.entryTime - w1.entryTime);
}
});
private PriorityQueue<e_time_p_time> awaitingOrders = new PriorityQueue<>(10, new Comparator<e_time_p_time>(){
//Order by the difference between entrytime and pizzaCookTime ASC
#Override public int compare(e_time_p_time w, e_time_p_time w1) {
return (int) (Math.abs(w.entryTime - w.pizzaCookTime) - Math.abs(w1.entryTime - w1.pizzaCookTime));
}
});
private long total = 0l;
public void insert(long customerWaitTime, long pizzaCookTime) {
incomingOrders.add(new e_time_p_time(customerWaitTime, pizzaCookTime));
}
public long calculateAverageWaitingTime() {
int size = incomingOrders.size();
e_time_p_time currentOrder = null;
e_time_p_time laterOrders = null;
while(incomingOrders.size() > 0) {
//Start by getting the customer that has the earliest arrival time (the queue is sorted that way)
currentOrder = incomingOrders.remove();
//Calculate it's waiting time.
total += currentOrder.entryTime + currentOrder.pizzaCookTime;
do {
/*Move all the customers that entered the shop while the current pizza is in the oven
to the awaitingOrders orders queue*/
laterOrders = incomingOrders.remove();
awaitingOrders.add(laterOrders);
} while (currentOrder.pizzaCookTime >= laterOrders.entryTime && incomingOrders.size() > 0);
//Go through awaitingOrders queue and calculate waiting time for the remaining orders
//(The queue is sorted as the difference between entrytime and pizzaCookTime ASC)
while(awaitingOrders.size() > 0) {
e_time_p_time shortestOrder = awaitingOrders.remove();
long waitTimeBeforeCooking = Math.abs((shortestOrder.entryTime + shortestOrder.pizzaCookTime) - currentOrder.entryTime);
total += waitTimeBeforeCooking;
}
}
//It's supposed to be the average time, but first I need the total to be correct, and right now, it's not...
System.out.println("\nTotal waiting time: ");
return total;
}
private static class e_time_p_time {
private long entryTime;
private long pizzaCookTime;
e_time_p_time(long entryTime, long pizzaCookTime) {
this.entryTime = entryTime;
this.pizzaCookTime = pizzaCookTime;
}
}
}
In this code:
do {
/*Move all the customers that entered the shop while the current pizza is in the oven
to the awaitingOrders orders queue*/
laterOrders = incomingOrders.remove();
awaitingOrders.add(laterOrders);
} while (currentOrder.pizzaCookTime >= laterOrders.entryTime && incomingOrders.size() > 0);
A couple of things seem wrong here:
You always add at least one item to awaitingOrders - but what if no-one enters the shop while the current pizza is in the oven? (e.g. for the last pizza)
You compare the pizzaCookTime - e.g. ten minutes, with the entryTime, e.g. 4pm. This doesn't seem right - shouldn't you compare the time that the pizza is completed with the entryTime?

Categories