Retrieve data from list by the most recent date java - java

I'm trying to collect data from my list (or group) with the most recent date for example the last monday. So I could then add values together then insert the new values back into the list.
Currently my output is looking like this
ID Date charge balance
1 29/07/2013 10 100
2 29/07/2013 20 200
3 29/07/2013 30 300
Give or take a few columns. The main purpose is to group for example the entries that are the 29th, add the charge to the balance create a new entry / field / row with the new balance and the system date.
So far I've create my list and I'm able to read in the entries from csv using a scanner but i have no idea how i can get the code to get the dates without hard coding.
public class Statements {
public int tncy_num;
//public double net_rent;
public String end_date;
public double bal_val;
public double chg_val;
public Statements(int t, String ed, double bv , double cv){
tncy_num = t;
//net_rent = nr;
end_date = ed;
bal_val = bv;
chg_val= cv;
}
public int getTncynum(){return tncy_num;}
//public double getNetRentnum(){return net_rent;}
public String getEndDatenum(){return end_date;}
public double getBalValnum(){return bal_val;}
public double getChgValnum(){return chg_val;}
//public double getBenfValnum(){return benf_val;}
//public double getAdjVal(){return adj_val;}
//public double getTotlValnum(){return totl_val;}
public String toString(){
return " "+this.getTncynum()+
" "+this.getEndDatenum()+
" "+this.getBalValnum()+
" "+this.getChgValnum();
}
}
I have a main driver class which has the main method(used to simply run the script), a coordinator class used to get the data and set the location of the csv file and other classes which return the data of the list.
public class Calculations {
private Coordinator cord;
private ArrayList Data;
public Calculations(Coordinator co) {
cord =co;
Data = new ArrayList<Statements>(cord.getData());
System.out.print(Data);
}
}

Implement a Collections.Sort which sort your list,
use JodaTime Library for Date http://joda-time.sourceforge.net/
Here an example :
Collections.sort(myList, new Comparator<Statements>() {
public int compare(Statements o1, Statements o2) {
if (o1.getEndDate() == null || o2.getEndDate() == null)
return 0;
return o1.getEndDate().compareTo(o2.getEndDate());
}
});

Related

How to format Java ArrayList with respective rows and columns and invoke the data of a column or a row?

I am a Java beginner, I have been trying to read a csv file from my computer by using Java and insert the data into a ArrayList.
public class DataRepository {
public void loadFile(){
ArrayList<String> binsGrade = new ArrayList<String>();
try {
Scanner fileScanner = new Scanner(new File("C:\\Users\\Max\\Desktop\\Grade_SampleData.csv"));
while(fileScanner.hasNextLine()){
binsGrade.add(fileScanner.nextLine());
}
fileScanner.close();
System.out.println(binsGrade);
} catch (FileNotFoundException e){
e.printStackTrace();
}
}
}
And below is the result I got:
[name,literature,math,physics,chemistry,biology,history,geology,art,sports, Michael,80,90,82,79,75,70,72,68,95, Amy,85,88,73,79,88,93,90,92,75, Johnson,72,89,81,84,83,72,89,90,82, Bob,80,81,84,89,87,90,71,65,89, Tommy,70,89,79,90,88,73,75,89,91, Rachel,90,91,80,92,87,92,95,97,87, Evonne,78,91,87,88,91,76,74,86,91]
All the records are in one row, but I actually want it to be in separated rows and columns, and for example, when I call name, I can get the value: Michael, Amy, Johson and etc. When I call literature, I can get 80, 85, 72, 80 and etc.Then I can probably use these data to do some calculation, like calculate the average, or get the maximum score and etc.
Although I have been searching online for a while, I still have not figured out the best way to achieve this. Can you please share your ideas if you have one minute? Your help will be really appreciated. Thanks!
If you want to have something implemented quickly, you can follow Srivenu comment and use a Map<String, List<String>>. Each entry of the Map will have the name as the key, and a list of string for all the results. For example to add Michael :
myMap.add("Michael", Arrays.asList({"20", "12", "8", "80"}));
Then create the different methods that will go through this map to compute the average, or find the max, etc
If you want a more oriented object approach I suggest you to create objects that will represent your data. First a result object that will contain two attributes, a string that will be the subject and an int that will be the score.
public class Result {
private String subject;
private int score;
public Result(String s, int i) {
subject = s;
score = i;
}
//Add Setters and Getters
//Add additional method if required
}
Secondly Have a Person object that wil represent someone. It will have two attributes, a String representing the name and a list of Results objects.
public class Person {
private String name;
private List<Result> results;
public Person(String s, List<Result> r) {
name = s;
results = r;
}
//Add getters and setters
//Add additional methods if required
/**
* Example of additional method
* This one will return the score for a given subject
**/
public int getScore(String subject) {
Result r = results.get(subject);
return r.getScore();
}
}
Thirdly, create a GroupOfPerson Class that will contain one attribute, a list of person. Then This class will have methods that will return the average, the max, etc...
public class GroupOfPerson {
private List<Person> persons;
public GroupOfPErson(List<Person> p) {
persons = p;
}
/**
* Example of method.
* This one will return the average score for the given subject
**/
public int getAverageForSubject(String subject) {
int average = 0;
for(Person p : persons) {
average += p.getScore(subject);
}
average /= persons.size();
return average;
}
//Add other methods
}
Finally when reading your CSV file, create the corresponding objects.

I have been asked to use arrays to store and manage objects

I have to create a storage system whenever a user gets fuel in their car. The data that needs to be stored is the date, car mileage, number of litres and the cost per litre. a separate class should be created to record these.
I should be able to add in the details of every transaction each time the person gets fuel.
Can anyone help get along the right lines and help me get started? below is my fuel logger class and i do not know how to create the fuel transaction class i was talking about.
public class FuelLogger
{
public static void main (String [] arguments)
{
FuelTransaction Ft1 = new FuelTransaction("10/01/2016", 500, 10, 0.99);
FuelTransaction Ft2 = new FuelTransaction("15/01/2016", 560, 10, 0.99);
FuelTransaction Ft3 = new FuelTransaction();
Ft3.setDate("24/01/2016");
Ft3.setCarMileage(670);
Ft3.setNumberOfLitres(15);
Ft3.setCostPerLitre(1.01);
Ft1.displayDetails();
Ft2.displayDetails();
Ft3.displayDetails();
//Amount of fuel bought between 2 dates
//System.out.println("The total amount of fuel between the two dates is " + FuelTransaction.getFuelAmount(Ft1, Ft3));
System.out.println("The total number of FuelTransactions is " + FuelTransaction.getTotalNum());
}
}
You can create a new Log object and add detail to the object in constructor and store it.
Maybe something like this:
public class FuelTransaction {
// Class variables
String date;
int mileage, numberOfLitres, costPerLitre;
// Constructor where we instantiate the FuelTransaction object
public FuelTransaction(String date, int mileage, int numberOfLitres, int costPerLitre) {
// Takes all the variables passed in and stores them to the class variable
this.date = date;
this.mileage = mileage;
this.numberOfLitres = numberOfLitres;
this.costPerLitre = costPerLitre;
}
public FuelTransaction() {
// Empty constructor, sets everything to "" or 0
this.date = "";
mileage = numberOfLitres = costPerLitre = 0;
}
public void setDate(String date) {
// Setter to set the date
this.date = date;
}
}
This isn't the complete class, you'll have to add to it but these are the basics. Notice how there are 2 constructors, this lets you initialize the FuelTransaction class by specifying all of the variables like new FuelTransaction(DATE, MILEAGE, NUMBEROFLITRES, COSTPERLITRE) but it also lets you call new FuelTransaction() and then manually add the data after instantiating with the setDate() setter:
FuelTransaction ft = new FuelTransaction();
ft.setDate("01-23-45");

Sort a list i java with two elements (type string and double) in Java

I am writing a pension program and I am stuck.
The program looks like this:
First I read in a file where every line has the name of the person, the age, and their first deposit.
I use a method called ReadFile to do that. Inside that method I call upon a class called class savingswhich is in a separate file to calculate their pension.
But I have the following problem: I would like to sort their names according to their pensions (highest to lowest) but I don't know how to do that.
Here is the method in the Readfile class:
#SuppressWarnings("resource")
public void readFile(double rate) {
while(scan1.hasNextLine()) {
String input = scan1.nextLine();
scan2 = new Scanner(input).useDelimiter("/");
String a = scan2.next();
int b = scan2.nextInt();
int c = scan2.nextInt();
// calculate savings
savings s = new savings();
s.totalSavings(a, b, c, rate);
// add savings to an array
}
}
1st, create a class say Person :
class Person{
private String name;
private int age;
private BigDecimal firstDeposit;
private BigDecimal pension;
//Setters and getters method
}
Now Create the List which will hold the information of every Person :
List<Person> personList=new ArrayList<Person>();
Now sort your list based on Pension :
Collections.sort(personList, new Comparator<Person>() {
public int compare(Person p1, Person p2) {
return p1.getPension().compareTo(p2.getPension());
}
});
Given you the hint to go about your problem, but as suggested by other users, kindly go through the basics of java.

Creating a method that works like ArrayList .add()

I'm writing a program that acts as a 'pocket' where the user is able to enter a kind of coin, such as, a quarter and the amount of quarters it has. I was assigned to do 3 different class, the Coin Class in which the coins and their values can be instatiated from, a Pocket Class, where I have to write a method that can add the coins of the user (basically the method would act like ArrayList .add() ) and the PocketClass tester. I have already written most of the code, but I am stuck as to how I could write the following method:
public void addCoin(String s, int i)
{
// s is type of coin, you are using s to instantiate a Coin and get value
// i is number of coins, you are using i to keep adding value to the totalValue
}
My question is how should I approach this? I am not quite clear on how to create method. Would I use a for-loop in order to keep track of the number of coins? I understand that the addCoin method works a lot like .add() from ArrayList.
Here is the code from my other classes:
public class Coin
{
private final String DOLLAR = "DOLLAR";
private final String QUARTER = "QUARTER";
private final String DIME = "DIME";
private final String NICKEL = "NICKEL";
private final String PENNY = "PENNY";
private int value;
private String coinName;
public Coin(String s,int count)//name of the coin and also the number of the coins you have
{
//Use if or switch statement to identify incoming string and provide value
double value=0;
if(DOLLAR.equalsIgnoreCase(s))
{
value=100.0;
}
else if(QUARTER.equalsIgnoreCase(s))
{
value=25.0;
}
else if(DIME.equalsIgnoreCase(s))
{
value=10.0;
}
else if(NICKEL.equalsIgnoreCase(s))
{
value=5.0;
}
else if(PENNY.equalsIgnoreCase(s))
{
value=1.0;
}
}
public int getValue()
{
return value;
}
}
and how the Pocket class is structured:
public class Pocket
{
private int currentValue;
private int totalValue;
private Coin quarter;
private Coin dime;
private Coin nickle;
private Coin penny;
public Pocket()
{ //Set initial value to zero
totalValue = 0;
currentValue = 0;
}
public void addCoin(String s, int i)
{
// s is type of coin, you are using s to instantiate a Coin and get value
// i is number of coins, you are using i to keep adding value to the totalValue
}
public int getValue()
{
return totalValue;
}
public void printTotal()
{
//print out two different output
}
}
I'm assuming you're adding the addCoin method in the Pocket class.
If you intend to keep track of the number of coins of each type within a Pocket, the simplest way to do so would be to declare a Hashmap that is keyed by the coin type (say, a "quarter" or a "dollar") and valued by the number of coins of that type. An invocation of the addCoin(type, count) method, say addCoin("dollar", 5) can then check if the hashmap already contains a key named "dollar" and if present, increment it's value by count.
I would suggest storing coins in a list so that you can add unlimited number of them.
Example:
class Coin{
//Same as your code....
public Coin(String coinType){
//..Same as your code, but removed number of coins
}
}
public class Pocket
{
private int currentValue;
private int totalValue;
//Create a list of coins to store unlimited number of coins
// A pocket can half 5 dimes
List coins;
public Pocket(){
//Set initial value to zero
totalValue = 0;
currentValue = 0;
coins = new ArrayList<Coin>();
}
/**
* This method will take only one coin at a time
**/
public void addCoin(String s){
Coin c = new Coin(s);
coins.add(c);
totalValue+=c.getValue();
}
/**
* This method will take any number of coins of same type
**/
public void addCoin(String s, int c){
//Add each one to array
for(int i=0;i<c;i++)[
addCoin(s);
}
}
}
I am not in favor of keeping multiple coin values in one Coin object because of the fact it is not a true representation of an object. What does that mean is tomorrow if you want to store other Coin attributes like "Printed Year", "President Picture on the coin" etc, you will have hard time. In my opinion it is better to represent one real world object (one coin here) using one object instance in the program,

How do I pull value from method designated with "this."

I have information like this:
xxx 0 1 2 ...
Name Fred0 Fred1 Fred2
Stamina 2 6 7
Intel 5 4 1
Heart 4 8 2
Speed 5 3 6
So, I was informed previously that creating a 2D ArrayList to store something like this is "archaic" and was provided with a different way to set my code up. The reason I was using ArrayList<> is because I want to be able to generate new racers as needed, rather than designating an array to a size. If I could just use a simple array this would have been done a week ago. Now I've been screwing with it for a week and I still don't get how it works.
public class test {
public String name;
private int stamina;
private int heart;
private int intel;
private int speed;
public ArrayList<String> racers = new ArrayList<String>();
private void racerInfo(String name) {
this.name = name;
this.stamina = (int) Math.floor(Math.random()*10);
this.heart = (int) Math.floor(Math.random()*10);
this.intel = (int) Math.floor(Math.random()*10);
this.speed = (int) Math.floor(Math.random()*10);
}
public void generate() {
for ( int i=0; i<=10; i++) {
String name = "Fred" + i;
System.out.println(name);
racerInfo(name);
racers.add(name);
}
}
public int getStamina() {
return this.stamina;
}
public int getHeart() {
return this.heart;
}
public int getIntel() {
return this.intel;
}
public int getSpeed() {
return this.speed;
}
}
public class main {
public static test test = new test();
public static void main(String[] args) {
test.generate();
//Put stuff here to pull stamina of Fred2 for example.
}
}
Now, in the main class. How would I do something that should be relatively simple like pulling the Stamina value for Fred2.
I've been following the exact directions I've been given by others here to write most of this code. But at this time, I'm getting to the point of just re-writing it all so that each stat (name, stamina, intel, speed, etc.) is just logged as a separate ArrayList<>. But I can't figure out how to make a 2D ArrayList containing the original ArrayLists ie.
ArrayList<String> name = new ArrayList<String>();
ArrayList<Integer> stamina = new ArrayList<Integer>();
ArrayList<ArrayList<Object>> arrayOfArray = new ArrayList<ArrayList<Object>>();
Yes, I know the arrayOfArray is probably done wrong, but, again, I just get told it's Archaic and nobody'll tell me how I can do it right so I can just go. arrayOfArray.get(2,1) and pull information that I want/need.
Sorry for the information overload here. but I'm trying to just find the best possible solution for what I want to do. If you can tell me how to correctly pull off either way I will be eternally grateful you you and all of your descendants.
First of you should refactor your class test to class Racer, which is a meaningful name and follows the convention to start classnames with an uppercase letter. Furthermore you should add Stamina, Intel, Heart and Speed to the constructor:
public Racer(String name, int stamina, int intel, int heart, int speed) {
this.name = name;
this.stamina = stamina;
this.intel = intel;
this.heart = heart;
this.speed = speed;
}
Now you can create your racer as following:
Racer fred2 = new Racer("Fred2", 7, 1, 2, 6);
You can store your values in a HashMap. HashMap is a collection consisting of key-value pairs. For the key you can use a string (the name of the racer) and as value you take an instance of your class Racer:
HashMap<String, Racer>() racerMap = new HashMap<>();
racerMap.put("Fred2", fred2);
This you can do in a for-loop for all of your racers. Now you can get the racer objects from your HashMap by calling the getMethod and putting the name as parameter in it. This will return an object of class Racer and you can call the getter methods on this object:
racerMap.get("Fred2").getSpeed();
or
racerMap.get("Fred2").getIntel();
Edit: I just saw your generate method. This method should return the HashMap of racers. In your main method you create a new HashMap:
HashMap<String, Racer> racerMap = generate();
Now you can use the map as described above.

Categories