ArrayList object sorting by time property [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I have two classes, MarathonAdmin and Runner.
I want to sort list (runners) holding objects of Runner class. I have done all
the coding up to the method sortRunnerList, which says sort the list. I have created
a compareTo method in Runner class and when I compare objects of Runner, they pick the default time values not the ones which I have assigned to objects generating random numbers (done in MarathonAdmin class).
Can someone help with this issue?
class Marathon
import java.util.*;
import java.io.*;
import ou.*;
import java.util.Random;
public class MarathonAdmin
{
// instance variables - replace the example below with your own
private List<Runner> runners;
private String ageGroup;
private String age;
private Random randomNumber;
private String result;
String ageRunner;
String ageGrouprunners;
Scanner lineScanner;
int ans ;
Runner runnerobj = new Runner();
Runner obj2 = new Runner();
public MarathonAdmin()
{
runners = new ArrayList<>();
}
public void readInRunners(){
String pathName = OUFileChooser.getFilename();
File aFile = new File(pathName);
String nameRunner;
BufferedReader bufferedFileReader = null;
try
{
bufferedFileReader = new BufferedReader(new FileReader(aFile));
String currentLine = bufferedFileReader.readLine();
while ( currentLine != null){
lineScanner = new Scanner(currentLine);
lineScanner.useDelimiter(",");
nameRunner = lineScanner.next();
ageRunner = lineScanner.next();
if (Integer.parseInt(ageRunner) < 18)
{
result = "junior";
System.out.println(currentLine +" category" + " : Junior");
}
if (Integer.parseInt(ageRunner) > 55)
{
result = "senior";
System.out.println(currentLine +" category"+ " : Senior");
}
if (Integer.parseInt(ageRunner) > 18 && Integer.parseInt(ageRunner) < 55)
{
result = "standard";
System.out.println(currentLine +" category"+ " : Standard");
}
ageGrouprunners = result;
Runner runnerobj = new Runner();
runnerobj.setName(nameRunner);
runnerobj.setAgeGroup(ageGrouprunners);
System.out.println(runnerobj); //rough test
runners.add(runnerobj);
currentLine = bufferedFileReader.readLine();
}
}
catch (Exception anException)
{
System.out.println("Error: " + anException);
}
finally
{
try
{
bufferedFileReader.close();
}
catch (Exception anException)
{
System.out.println("Error: " + anException);
}
}
}
public void runMarathon(){
int size = runners.size();
// for ( int runnersIndex = 0; runnersIndex <= size; runnersIndex ++ ){
for( Runner nameRunner : runners){
this.randomNumber = new Random();
ans = randomNumber.nextInt(190 - 80 +1 ) + 90 ;
System.out.println(ans);
nameRunner.setTime(ans);
}
}
public void sortRunnerList(){
for(Runner nameRunner : runners){
int time = nameRunner.getTime();
System.out.println(time);
Runner obj = new Runner();
obj.setTime(ans);
int res = nameRunner.compareTo(obj);
System.out.println(res);
}
}
}
//(This is method of class Runner)
Class Runner
Method compareTo()
#Override
public int compareTo(Runner anotherRunner)
{
return this.getTime()-(anotherRunner.getTime());
}

Try replacing
return this.getTime()-(anotherRunner.getTime());
with
return Integer.valueOf(this.getTime()).compareTo(anotherRunner.getTime());

Related

How do I make a class to dynamic check different objects variable?

I'm new to Java, and i'm trying to create an automatic working shift schedule.
I want the code to mix four different employees to handle a morning shift and afternoon shift every work day.
I have made some code that just pick a random employee into a shift:
import java.util.Arrays;
import java.util.Random;
public class CreateNewShift {
public static void main(String[] args) {
int startWeek = 30; //Which week would start from?
int endWeek = 32; //which week will you end on?
generateShift(startWeek, endWeek);
}
private static void generateShift(int startWeek, int endWeek) {
String Employees[] = {"Employee1", "Employee2", "Employee3", "Employee4"};
String morningShift;
String afternoonShift;
for (int x = 0; x <= (endWeek - startWeek); x++) { //This is counting the number of weeks
System.out.println("\nWeek: " + (startWeek+x));
for (int i = 1; i <= 5; i++) { //this is finding the next working shift day
morningShift = p.chooseRandomEmployee(Employees);
afternoonShift = p.chooseRandomEmployee(Employees);
if (i == 1) {
System.out.println("Mon: " + morningShift + " + " + afternoonShift);
}
else if (i == 2) {
System.out.println("Tue: " + morningShift + " + " + afternoonShift);
}
else if (i == 3) {
System.out.println("Wed: " + morningShift + " + " + afternoonShift);
}
else if (i == 4) {
System.out.println("Thu: " + morningShift + " + " + afternoonShift);
}
else {
System.out.println("Fri: " + morningShift + " + " + afternoonShift);
}
}
}
}
public class Employee {
public String chooseRandomEmployee(String[] Employees) {
Random r = new Random();
int randomNumber = r.nextInt(Employees.length);
return Employees[randomNumber];
}
}
However, I now want the code to handle more restictions.
So i'm currently trying to add the option for the employees to choose some specific days that they dont want to have a shift. I have done this by adding this code to the Employee class:
public class Employee {
boolean monShift = true;
boolean tueShift = true;
boolean wedShift = true;
boolean thuShift = true;
boolean friShift = true;
public String chooseRandomEmployee(String[] Employees) {
Random r = new Random();
int randomNumber = r.nextInt(Employees.length);
return Employees[randomNumber];
}
}
And then i had tried to create new objects in my main class:
private static void generateShift(int startWeek, int endWeek) {
Employee Employee1 = new Employee("Employee1");
Employee Employee2 = new Employee("Employee2");
Employee Employee3 = new Employee("Employee3");
Employee Employee4 = new Employee("Employee4");
String Employees[] = {"Employee1", "Employee2", "Employee3", "Employee4"};
String morningShift;
String afternoonShift;
....
Quetions:
How can I improve my code in the Employee class to do a check if the random chosen employee have
monShift = true;
I have tried something like this, but i know it will not work, (and does not work either):
import java.util.Random;
public class Employee {
public String chooseRandomEmployee(String[] Employees) {
Random r = new Random();
int randomNumber = r.nextInt(Employees.length);
**if (("Employee" + randomNumber).monShift == false) {**
// Go back and try find a new random employee
}
else {
return Employees[randomNumber];
}
}
}
So i need a way to make my code dynamic to know which object (employee) it has to check if they are available that specific day or not.
Feel free to ask for a deepening if my question is not clear.
Since this i my first question on this forum, I also appriciate feedback if my question and thoughts are too long, or any other comments.
I dont think that putting the chooseRandomEmployee() function inside the Employee object is a good idea beacuse is not a part of the employee, is not an "action" of it. I think you shiudl put it outside but I want to respect your decision so shoudl check the do while loop.
import java.util.Random;
public class Employee {
public String chooseRandomEmployee(String[] Employees) {
int randomNumber;
do {
//Generate a new random number
Random r = new Random();
randomNumber = r.nextInt(Employees.length);
//The line under is the same that saying "If monSift == false return to
//the beginning and start again generating a new number"
} while ("Employee" + randomNumber).monShift == false);
return Employees[randomNumber];
}
}

How do i pass variables into methods - java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I need to use a variable from one method in another. Here is the code:
public static void secondMain() {
BufferedReader reader;
var lines = new ArrayList<String>();
var rooms = new ArrayList<Room>();
try {
reader = new BufferedReader(new FileReader("rooms.txt"));
String line = reader.readLine();
lines.add(line);
while (line != null) {
line = reader.readLine();
lines.add(line);
}
reader.close();
for (int i = 0; i < lines.size() - 1; i++){
String[] words = lines.get(i).split(" ");
var room = new Room();
room.roomNum = Integer.parseInt(words[0]);
room.roomType = (words[1]);
room.roomPrice = Double.parseDouble(words[2]);
room.hasBalcony = Boolean.parseBoolean(words[3]);
room.hasLounge = Boolean.parseBoolean(words[4]);
room.eMail = (words[5]);
rooms.add(room);
}
Here is where it needs to be used:
public static void reserveRoom() {
// TODO Auto-generated method stub
String choice = "";
do {
secondMain();
System.out.println("\n-- ROOM RESERVATION --");
System.out.println("Please enter the room number you wish to reserve");
System.out.println("Q - Quit");
Room selectedRoom = null;
var searchRoomNum = input.nextInt();
for(int i = 0; i < rooms.size(); i++){
if(rooms.get(i).roomNum == searchRoomNum){
selectedRoom = rooms.get(i);
System.out.println("Room Number: " + selectedRoom.roomNum);
System.out.println("Room Type: " + selectedRoom.roomType);
System.out.println("Room Price: " + selectedRoom.roomPrice);
System.out.println("Balcony: " + selectedRoom.hasBalcony);
System.out.println("Lounge: " + selectedRoom.hasLounge);
System.out.println("Email: " + selectedRoom.eMail);
System.out.println("-------------------");
}
}
}
my current error is on the for loop where im testing the conditions against the array. "rooms cannot be resolved".
If you want to access rooms from the secondMain() method in the reserveRoom(), you should return it from secondMain() when you make the call. This can be done by changing the return type of the method
public static void secondMain() to become public static ArrayList<Room> secondMain()
Then after the for loop in secondMain() when you have finished adding all the rooms to the array list, you should return rooms to the caller. This can be added as one statement after your try catch block.
return rooms;
This way you can access this property from reserveRoom(). The line where the call is made
do {
secondMain();
should become:
do{
var rooms = secondMain();
This should allow you to access rooms in reserveRoom()
Instead of public static void secondMain, you can make it public static ArrayList<Room> secondMain
At the end of the secondMain: return rooms.
In the reserveRoom method: when you call the secondMain method: ArrayList<Room> rooms = secondMain();
Now you should be able to use rooms inside reserveRoom method

NumberFormatException Error - Reading from file and parsing input as number

I'm having trouble figuring out what's wrong with my java code. I am creating a Trivia Game that reads in the question ID, question, answer, and answer point value from a dat file.
I've tried all sorts of things, but am getting the same NumberFormatException.
Below is an example of how the dat file is setup: 10 questions total
1: 01
2: What is light as a feather, but even the strongest man cannot hold it more
than a few minutes?
3: His breath
4: 3
Game.java
import java.util.*;
import java.io.*;
public class Game {
// Instance Variables
private QuestionBank[] questions;
private int numQuestions;
private int questionNumber;
private int playerScore;
// Constructor
public Game()
{
QuestionBank[] questions = new QuestionBank[10];
numQuestions = 0;
questionNumber = 0;
playerScore = 0;
}
public Game(FileInputStream questionsFile)
{
BufferedReader br = new BufferedReader(new InputStreamReader(questionsFile));
String stringLine = null;
int i = 0;
try
{
while((stringLine = br.readLine()) != null)
{
QuestionBank quest = new QuestionBank();
quest.setQuestionID(Integer.valueOf(br.readLine())); //ERROR OCCURS HERE
quest.setQuestion(br.readLine());
quest.setAnswer(br.readLine());
quest.setPointValue(Integer.valueOf(br.readLine()));
questions[i] = quest;
i++;
stringLine = null;
}
br.close();
}
catch (IOException e)
{
System.out.println("Uh oh. Exception caught.");
}
this.questionNumber = 0;
/*Scanner questionsFileScanner = new Scanner(questionsFile);
questions = new QuestionBank[5];
while(questionsFileScanner.hasNextLine())
{
for(int i = 0; i < 4; ++i)
{
questions[i] = new QuestionBank();
questions[i].setQuestion(questionsFileScanner.nextLine());
}
}*/
}
//Accessors and Mutators
public int getNumQuestions()
{
return numQuestions;
}
public int getQuestionNumber()
{
return questionNumber;
}
public int getPlayerSocre()
{
return playerScore;
}
public boolean checkAnswer(String answer)
{
if(answer.contentEquals(questions[questionNumber].getAnswer()) == true)
{
playerScore += questions[questionNumber].getPointValue();
++questionNumber;
return true;
}
else
{
return false;
}
}
public String getNextQuestion()
{
return questions[questionNumber].getQuestion();
}
public String toString()
{
String outputString = "";
for (int i = 0; i < questionNumber; ++i)
{
outputString = questions[i].toString();
}
return outputString;
}
}
Exception in thread "main" java.lang.NumberFormatException: For input string: "What is light as a feather, but even the strongest man cannot hold it more than a few minutes?"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.valueOf(Integer.java:983)
at project7.Game.<init>(Game.java:41)
at project7.RunGame.main(RunGame.java:41)
In addition to what I mentioned above you can use StringUtils.isNumeric method to see if stringLine only contains numeric values.
You can find that method with Apache Commons Lang dependency.
if you're using maven here's the link to download it to your project https://mvnrepository.com/artifact/org.apache.commons/commons-lang3/3.5
If you're not using maven you should be able to download the jar from that link (or from https://jar-download.com/artifacts/org.apache.commons/commons-lang3/3.5/source-code) and then include the jar as a library in your project.

Error message while using inheritance in java

I am new to inheritance in java and I have the folowing problem. My base class is Plane, its child class is PlaneComponent and PlaneComponent's child class is PassengerCompartment. My program consists of 11 classes, when I ignore the PassengerCompartment class everythig's right. But when I run the whole program I get this message: at Plane.<init>(Plane.java:14)
at PlaneComponent.<init>(PlaneComponent.java:1)
at PassengerCompartment.<init>(PassengerCompartment.java:11)
which is printed repeatedly for so many times that I cannot see the top line of the error. The lines includes in error messages are the bold lines (here printed between ** **).
Plane:
import java.util.*;
public class Plane
{
int cap;
int pl;
public Plane()
{
String desc = "Plane Description";
String title = "Boeing 747";
Random rand = new Random();
cap = rand.nextInt(100) + 51; //initialize cap with 50<value<100
**PassengerCompartment a8 = new PassengerCompartment();**
pl = cap / a8.cap2; // pl = sum of Passenger Compartments
if (cap % a8.cap2 != 0)
{
pl = pl - (cap % a8.cap2) + 1;
}
}
public boolean ready_check()
{
CargoBay a6 = new CargoBay();
a6.ready_check();
for (int i = 0 ; i < 3 ; i++)
{
EquipmentCompartment a7 = new EquipmentCompartment();
a7.ready_check();
}
for(int i = 0; i < pl; i++)
{
PassengerCompartment a8 = new PassengerCompartment();
a8.ready_check();
}
System.out.println("Plane OK!");
return true;
}
public void process(String e)
{
if(e == "SecurityEmployee")
{
SecurityEmployee a14 = new SecurityEmployee();
a14.workOn();
}
if(e == "MaintenanceEmployee")
{
MaintenanceEmployee a15 = new MaintenanceEmployee();
a15.workOn();
}
if(e == "CleaningEmployee")
{
CleaningEmployee a16 = new CleaningEmployee();
a16.workOn();
}
}
public void values()
{
System.out.println("Would you like more info about the plane's capacity? type Y or N");
Scanner input = new Scanner(System.in);
String inp = input.nextLine();
while (!(inp.equals("Y")) && !(inp.equals("N")))
{
System.out.println("Wrong input, please type again");
inp = input.nextLine();
}
if ( inp.equals("Y"))
{
PassengerCompartment a8 = new PassengerCompartment();
System.out.println("Plane's capacity: " + cap);
System.out.println("PassComp's capacity: " + a8.cap2);
System.out.println("Number ofPassenger Compartments " + pl);
}
}
}
PlaneComponent:
**public class PlaneComponent extends Plane**
{
public boolean ready_check()
{
return true;
}
public void process(String desc)
{
Employee.workOn(desc);
}
}
PassengerCompartment:
import java.util.*;
public class PassengerCompartment extends PlaneComponent
{
Random rand = new Random();
boolean inner = rand.nextBoolean();
int cap2;
String desc;
public PassengerCompartment()
**{**
desc = "Passenger Compartment";
cap2 = rand.nextInt(50) + 21; //initialize cap with 20<value<50
}
public boolean ready_check()
{
System.out.println(desc);
if (super.ready_check() == true)
{
System.out.println("Passenger Compartment OK!");
if (inner == true)
{
desc = "Inner Compartment";
System.out.println(desc);
if (super.ready_check() == true)
{
System.out.println("Inner Compartment OK!");
}
}
}
return true;
}
public void process(String desc)
{
super.process(desc);
}
}
You have a circular-inheritance-kind-of-situation (which probably creates a StackOverflow exception):
You instantiate PassengerCompartment a8 = new PassengerCompartment(); in the constructor of Plane.
PassengerCompartment extends PlaneComponent, so the constructor of PlaneComponent is called implicitly (super()), which inherit from Plane. In Plane's constructor you have the mentioned instantiation of PassengerCompartment and so on... So I would strongly advise to not instantiate classes that inherit from your class in the constructor of said class.
I would recommend reading my Q/A on this very topic here.
Your issue is with your inheritance structure.
In Planes constructor, you create an instance of PassengerCompartment.
PassengerCompartment extends PlaneCompartment. PlaneCompartment extends `Plane'. So, you are in a circle.
I don't think it makes sense for PlaneCompartment to extends Plane.
What you have is a 'has-a' relationship. So, Plane has a PlaneCompartment but neither extends each other.

read line using java & maped filterd data [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
public class Reader {
public static void main(String[] args) throws IOException, ParseException {
BufferedReader reader;
String animalName="cat";
String animal = null;
try {
reader = new BufferedReader(new InputStreamReader(
new FileInputStream("C:/dila.txt")));
Map<String, Integer> result = new LinkedHashMap<String, Integer>();
Map<String, Integer> result2 = new LinkedHashMap<String, Integer>();
while (reader.ready()) {
String line = reader.readLine();
/split a line with spaces/
String[] values = line.split(",");
String key = null;
if(values[1].compareTo(animalName)==0){
key = values[0];
animal=""+values[1].compareTo(animalName);
int sum = 0;
int count = 0;
/get a last counter and sum/
if (result.containsKey(key)) {
sum = result.get(key);
count = result2.get(key);
} else{
}
/increment sum a count and save in the map with key/
result.put(key, sum + Integer.parseInt(values[2]));
result2.put(key, count + 1);
}
}
/interate and print new output/
for (String key : result.keySet()) {
Integer sum = result.get(key);
Integer count = result2.get(key);
System.out.println(key +" "+animalName+ " " + sum + "\t" + count);
}
reader.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
i have below text file
11/2/2010,cat,6
11/2/2010,cat,3
11/2/2010,dog,4
11/2/2010,cat,11
11/3/2010,cat,1
11/3/2010,dog,3
11/3/2010,cat,8
11/3/2010,cat,80
The above code is currently printing this summary data
11/2/2010 cat 20 3
11/3/2010 cat 104 4
11/4/2010 cat 26 2
I need help is printing the summary as shown below
11/01/2010
11/02/2010 cat 20 3
11/03/2010 cat 104 4
11/04/2010 cat 26 2
11/05/2010
11/06/2010
11/07/2010
11/08/2010
11/09/2010
11/10/2010
11/11/2010
11/12/2010
11/13/2010
11/14/2010
11/15/2010
11/16/2010
11/17/2010
11/18/2010
11/19/2010
11/20/2010
11/21/2010
11/22/2010
11/23/2010
11/24/2010
11/25/2010
11/26/2010
11/27/2010
11/28/2010
11/29/2010
11/30/2010
i hav bulk of data seperated from "," . so iwant to read line and split. & i hav done it. but my requrment is above shown result.
Below is the code to do it. I am taking help of google-guava libraries as it helps me write less code ;-). If you just want in plain java then you can modify the code also if the logic needs some tweaking then look at processLine(...) method, that is where the change will go
Ok the only missing code I see is printing empty data for the dates that are not part of the input file in a sorted order. That is simple and leave it to you. Here is the hint: Increment date by 1 & loop until end of the month
I have run your sample file and it prints the below summary
11/3/2010 cat 89 3
11/3/2010 dog 3 1
11/2/2010 dog 4 1
11/2/2010 cat 20 3
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import com.google.common.base.CharMatcher;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Maps;
import com.google.common.io.Files;
import com.google.common.io.LineProcessor;
public class AnimalSummaryBuilder
{
private static final Splitter SPLITTER = Splitter.on(CharMatcher.anyOf(","));
private static final Joiner JOINER = Joiner.on("\t");
#SuppressWarnings("unchecked")
public static void main(final String[] args) throws Exception
{
#SuppressWarnings("rawtypes")
Map<Animal, Summary> result = Files.readLines(new File("c:/1.txt"), Charsets.ISO_8859_1, new LineProcessor() {
private final Map<Animal, Summary> result = Maps.newHashMap();
public Object getResult()
{
return result;
}
public boolean processLine(final String line) throws IOException
{
Iterator<String> columns = SPLITTER.split(line).iterator();
String date = columns.next();
String name = columns.next();
int value = Integer.valueOf(columns.next()).intValue();
Animal currentRow = new Animal(date, name);
if (result.containsKey(currentRow))
{
Summary summary = result.get(currentRow);
summary.increaseCount();
summary.addToTotal(value);
}
else
{
Summary initialSummary = new Summary();
initialSummary.setCount(1);
initialSummary.setTotal(value);
result.put(currentRow, initialSummary);
}
return true;
}
});
for (Map.Entry<Animal, Summary> entry : result.entrySet())
{
Animal animal = entry.getKey();
Summary summary = entry.getValue();
System.out.println(JOINER.join(animal.date, animal.name, summary.total, summary.count));
}
}
final static class Animal
{
String date;
String name;
public Animal(final String date, final String n)
{
this.date = date;
this.name = n;
}
#Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((date == null) ? 0 : date.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
#Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (!(obj instanceof Animal))
{
return false;
}
Animal other = (Animal) obj;
if (date == null)
{
if (other.date != null)
{
return false;
}
}
else if (!date.equals(other.date))
{
return false;
}
if (name == null)
{
if (other.name != null)
{
return false;
}
}
else if (!name.equals(other.name))
{
return false;
}
return true;
}
}
final static class Summary
{
private int total;
private int count;
void setTotal(int value)
{
total = value;
}
void setCount(int i)
{
count = i;
}
void increaseCount()
{
count++;
}
void addToTotal(int valueToAdd)
{
total += valueToAdd;
}
}
}
You could use another map with the date as the key, and the results you got as value. Then you just loop through all the days in the month, and if the map contains the current date key, you print the corresponding value, else you only print the date.
Here is the dirty solution. The assumption is that the "result" map contains only 1 month.
public class Reader
{
public static void main(final String[] args) throws ParseException
{
BufferedReader reader = null;
String animalName = "cat";
// String animal = null;
try
{
reader = new BufferedReader(new InputStreamReader(new FileInputStream("C:/1.txt")));
Map<String, Integer> result = new LinkedHashMap<String, Integer>();
Map<String, Integer> result2 = new LinkedHashMap<String, Integer>();
while (reader.ready())
{
String line = reader.readLine();
// split a line with spaces
String[] values = line.split(",");
String key = null;
if (values[1].compareTo(animalName) == 0)
{
key = values[0];
// animal=""+ ""+values[1].compareTo(animalName);
int sum = 0;
int count = 0;
// get a last counter and sum
if (result.containsKey(key))
{
sum = result.get(key);
count = result2.get(key);
}
else
{
}
// increment sum a count and save in the map with key
result.put(key, sum + Integer.parseInt(values[2]));
result2.put(key, count + 1);
}
}
String date = result.keySet().iterator().next();
DateFormat df = new SimpleDateFormat("mm/dd/yyyy");
Calendar calendar = Calendar.getInstance();
calendar.setTime(df.parse(date));
int monthStart = calendar.getActualMinimum(Calendar.DAY_OF_MONTH);
int monthEnd = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
calendar.set(Calendar.DAY_OF_MONTH, 0);
// interate and print new output
for (int i = monthStart; i < monthEnd; i++)
{
calendar.add(Calendar.DAY_OF_MONTH, 1);
String key = df.format(calendar.getTime());
if (result.containsKey(key))
{
Integer sum = result.get(key);
Integer count = result2.get(key);
System.out.println(key + " " + animalName + " " + sum + "\t" + count);
}
System.out.println(key);
}
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try
{
reader.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

Categories