I have a text file of cars with the following structure:
21
Vauxhall
Corsa
red
19
Vauxhall
Corsa
blue
18
Vauxhall
Corsa
White
I can load it into a HashMap but when I load it, it indexes every new line as a new element. How do I change this so after every 4 lines, it indexes?
Is there a way that I can also make it load into a elements such as:
id
Manufacturer
carMake
carColour
Hope this is what you wanted....
public static void main(String[] args) throws IOException {
Map<Integer, String> map = new HashMap<Integer, String>();
BufferedReader reader = new BufferedReader(new FileReader("/home/Desktop/cars.txt"));
String line = "";
int i = 0;
while (line != null) {
String data = "";
for (int k = 0; k < 4; k++) {
data = data + "," + reader.readLine();
if (k == 3)
map.put(i, data);
}
line = reader.readLine();
i++;
}
System.out.println(map);
}
You should create a new POJO class for the Car and then populate the data you read from the text file in that POJO.
Also, I don't see any use of a HashMap as you are just adding the incremented counter as key. You can use a HashSet instead.
Here is the code snippet
public class Car {
private int id;
private String manufacturer;
private String carMake;
private String carColour;
/* Getter Setters */
}
Main Class:
Set<Car> set= new HashSet<>();
BufferedReader reader = new BufferedReader(new FileReader("cars.txt"));
String line = "";
while (line != null) {
Car car = new Car();
line = reader.readLine();
car.setId(line != null ? reader.readLine() : 0);
line = reader.readLine();
car.setManufacturer(line != null ? reader.readLine() : null);
line = reader.readLine();
car.setCarMake(line != null ? reader.readLine() : null);
line = reader.readLine();
car.setCarColour(line != null ? reader.readLine() : null);
set.add(car);
}
What you wrote will read each line an treat it same, as strings, and as such, you place it in the map. Java is OOP, so use it, create an object, place 4 variables for each line from car string group and then have a HashMap of such objects. Like:
public class Car {
private int id;
private String something;
private String type;
private String collor;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSomething() {
return something;
}
public void setSomething(String something) {
this.something = something;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getCollor() {
return collor;
}
public void setCollor(String collor) {
this.collor = collor;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Car car = (Car) o;
return id == car.id;
}
#Override
public int hashCode() {
return id;
}
#Override
public String toString() {
return "Car{" +
"id=" + id +
", something='" + something + '\'' +
", type='" + type + '\'' +
", collor='" + collor + '\'' +
'}';
}
}
Make sure you have toString, hashCode and equals method in such objects, they are very important!
If you dont want to create a Car object with those four elements you could do this using Map of Integer and List<String>.
Map<Integer, List<String>> map = new HashMap<Integer, List<String>>();
BufferedReader reader = new BufferedReader(new FileReader("cars.txt"));
String line="";
int i=0;
List<String> list = new ArrayList<String>();
while (line != null) {
line = reader.readLine();
if (line == null || line.trim().equals("")) continue;
list.add(line);
if (i % 4 == 0) {
map.put(list.get(0), list);
list = new ArrayList<String>();
}
i++;
}
Create a Car bean and give it a constructor to build the object reading the file lines.
Once create the Car will add itself into the map.
static class Car{
String id;
String Manufacturer;
String carMake;
String carColour;
public Car(BufferedReader reader, Map<Integer, Car> map) throws Exception{
id = readLine(reader);
Manufacturer = readLine(reader);
carMake = readLine(reader);
carColour = readLine(reader);
map.put(map.size(), this);
}
private String readLine(BufferedReader reader) throws Exception{
String s = reader.readLine();
if(s == null){
throw new Exception("No more line...");
}
return s;
}
}
public static void main(String[] args) {
try{
Map<Integer, Car> map = new HashMap<Integer, Car>();
BufferedReader reader = new BufferedReader(new FileReader("cars.txt"));
try{
while (true) {
new Car(reader, map);
}
}catch(Exception e){
// Will be thrown at the end ov the file
}
for(int j=0;j<map.size();j++){
System.out.println(map.get(j));
}
System.out.println(map);
}catch(Exception e){
e.printStackTrace();
}
}
First you should understood what you are actually doing.
This loop that you are using to read file, reads every single line and put in in map under index i (it doesn't care what it actually got).
while (line != null) {
line = reader.readLine();
map.put(i,line);
i++;
}
So for your purpose you need to discern what data you are excepting in that loop.
{
id = reader.readLine();
Manufacturer = reader.readLine();
carMake = reader.readLine();
carColour = reader.readLine();
reader.readLine(); //empty space between data
...
}
Of course it would be good to check if you are getting any data, like putting it in if statements.
Your next move should be deciding how you want to store that data. There are many ways to do so. For example you could also use another hashMap
Map<Integer, Map<String>> map = new HashMap<>();
...
{
...
Map<String, String> car = new HashMap<>();
car.put("id", id);
car.put("manufacturer", manufacturer);
car.put("model", carMake);
car.put("color", carColor);
map.put(i, car);
}
EDIT:
Almost forgot, since your file have space between each car data, there is a need to read that empty line and ignore it
Related
I want to make a program that updates the hashmap depending on the user input commands. How can I remove/update specific element of a hashmap by passing id variable of Student class as user input?
This is what I got so far:
class Student{
String name;
String secondname;
int id;
public Student(String name,String secondname,int id){
this.id = id;
this.name = name;
this.secondname=secondname;
}
public int getId(){
return this.id;
}
#Override
public String toString() {
return "Second Name: "+ this.secondname+ " Name: "+ this.name+ " ID: "+ this.id;
}
#Override
public boolean equals(Object o) {
if(this==o){
return true;
}
if (o==null){
return false;
}
if(getClass() != o.getClass()){
return false;
}
Student obj = (Student) o;
if (secondname == null) {
if(obj.secondname!= null){
return false;
}
}
else if(!secondname.equals(obj.secondname)){
return false;
}
if(name==null){
if(obj.name!=null){
return false;
}
}
else if(!name.equals(obj.name)){
return false;
}
if(getId()==0){
if(obj.getId()!=0){
return false;
}
}
else if (getId()!=obj.getId()){
return false;
}
return true;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result= prime*result+id;
return result;
}
public class Main {
public static void main(String[] args) {
HashMap<Student,String> studentmap = new HashMap<>();
Student myname = new Student("Name","SecondName",1234);
Student mrx = new Student("Mr","X",2077);
Student msx = new Student("Ms","X",1111);
studentmap.put(myname,"A");
studentmap.put(mrx,"C");
studentmap.put(msx,"B");
while (true){
Scanner scan = new Scanner(System.in);
String x= scan.nextLine();
if (x.equals("add")){
System.out.println("Who do you want to add? ");
String y= scan.nextLine();
String [] splitted = y.split("\\s+");
studentmap.put(new Student(splitted[0],splitted[1],Integer.parseInt(splitted[2])),splitted[3]);
}
if(x.equals("remove")){
System.out.println("Who do you want to remove?");
String z= scan.nextLine();
int theid = Integer.parseint(z);
studentmap.remove(theid); // adding and printing works but this is what I have problem with
}
//if (x.equals("update")){
//String e= scan.nextLine();
//String [] splitted = e.split("\\s+");
//int theid = Integer.parseint(splited[0])
//studentmap.replace(theid,splitted[1]);
//}
if(x.equals("print")){
studenci.entrySet().forEach(entry->{
System.out.println(entry.getKey() + " Grade: " + entry.getValue());
});
}
if (x.equals("end")){
break;
}
}
}
The way I want this program to work is to make the user type a command like "delete", then make him type ID ex."1234" and then remove a hash map object whose Key's ID is 1234.
EDIT:
My assignment roughly translated to english:
Make a program using a map which keys are Student class objects (with fields: name ,secondname, id ), and the values are grades.
Program should allow the user to add, delete, update the grade and print the students list. In case of deleting and updating look up the object by ID.
You have to "find" the key from the Map<Student,String> first, which matches the id you have. After that you can use it to remove the entry from the Map<Student,String>. The code might look like this:
Student s = null;
for(Student k: studentmap.keySet()) {
if (k.getId() == theid) {
s = k;
break;
}
}
This will find you the key in the Map. After that you can remove the entry:
if (s != null) {
studentmap.remove(s);
}
It'd make more sense to change:
HashMap<Student,String> studentmap = new HashMap<>();
Student myname = new Student("Name","SecondName",1234);
Student mrx = new Student("Mr","X",2077);
Student msx = new Student("Ms","X",1111);
studentmap.put(myname,"A");
studentmap.put(mrx,"C");
studentmap.put(msx,"B");
Into:
HashMap<Integer,Student> studentmap = new HashMap<>();
Student myname = new Student("Name","SecondName",1234);
Student mrx = new Student("Mr","X",2077);
Student msx = new Student("Ms","X",1111);
studentmap.put( yname.getId(),myname);
studentmap.put(mrx.getId(),mrx);
studentmap.put(msx.getId(),msx);
Then when someone types 'remove', followed by the Id, you can delete like you want/wrote:
studentmap.remove(theid); // remove student 'myname' if 1234
I have to write this program for lab. I have to basically illustrate exactly what a hashmap is (keys and values) and the basic operations of declaration, .add(), .get(), and how to get the keys and values from the map. You will then apply this to the frequency histogram problem using the woodchucks.txt input file. I've done all this but I'm stuck on how to write my method that prints the histogram. Can someone please help me out?
import java.io.*;
import java.util.*;
public class Lab8
{
public static void main(String args[]) throws Exception
{
BufferedReader infile = new BufferedReader(new FileReader(args[0]));
HashMap<String,Integer> histogram = new HashMap<String,Integer>();
String word;
while ( (word = infile.ready()) != null )
{
if(histogram.get(word)==null)
histogram.put(word,1);
else
histogram.put(word, histogram.get(word)+1);
}
// YOUR CODE HERE
infile.close();
printHistogram( histogram );
} // END MAIN
// YOU FILL IN THIS METHOD
// READ PROBLEM SPECIFICATION TO SEE WHAT IS THE 80% vs 100% CREDIT SOLUTION
private static void printHistogram( HashMap<String,Integer> hm )
{
// YOU CODE HERE
}
} // END LAB8 CLASS
Would I print the histogram like this?
for ( int i = 0; i < histogram.length; i++ )
{
output += "\n" + i + "\t" + histogram[ i ] + "\t";
for ( int j = 1; j <= histogram[ i ]; j++ )
So if i'll be doing this, i would start from creating two classes, one where i could hold word and number occurrences such as my HistogramItem
public class HistogramItem implements Comparable<HistogramItem> {
#Override
public String toString() {
return "HistogramItem [word=" + word + ", occurence=" + occurence
+ "]";
}
public int getOccurence() {
return occurence;
}
public void updateOccurence() {
this.occurence++;
}
public String getWord() {
return word;
}
public HistogramItem(String word) {
super();
this.word = word;
}
private final String word;
private int occurence = 0;
#Override
public int compareTo(HistogramItem o) {
if (occurence == o.occurence) {
return word.compareTo(o.word);
}
return o.occurence-occurence;
}
}
and other one which will be my actual histogram
public class Histogram {
private Map<String, HistogramItem> map = new HashMap<>();
private List<HistogramItem> list = new ArrayList<>();
public void addWord(String word) {
HistogramItem item = map.get(word);
if (item == null) {
item = new HistogramItem(word);
map.put(word, item);
list.add(item);
}
item.updateOccurence();
}
public List<HistogramItem> getList() {
Collections.sort(list);
return list;
}
}
i'm using two collections, hashmap, because search for entry is much quicker than in list, but list is much easier to sort, list can be created and sorted when requested
How this fits your original excercise? Simple
public static void main(String args[]) throws Exception
{
BufferedReader infile = new BufferedReader(new FileReader(args[0]));
Histogram histogram = new Histogram();
String word;
while ( (word = infile.ready()) != null )
{
histogram.addWord(w);
}
// YOUR CODE HERE
infile.close();
// Below line prints histogram, can be placed in printHistogram method
for (HistogramItem item : histogram.getList()) {
System.out.println(item.toString());
}
} // END MAIN
I figured it out and this is the answer...
import java.io.*;
import java.util.*;
public class Lab8
{
public static void main(String args[]) throws Exception
{
BufferedReader infile = new BufferedReader(new FileReader(args[0]));
HashMap<String,Integer> histogram = new HashMap<String,Integer>();
String word;
while ((infile.ready()))
{
word = infile.readLine();
if(histogram.get(word)== null) //if the word your currently on is not duplicated
{
histogram.put(word,1);
}
else
{
histogram.put(word, histogram.get(word)+1);
}
}
// YOUR CODE HERE
infile.close();
printHistogram( histogram );
} // END MAIN
// YOU FILL IN THIS METHOD
// READ PROBLEM SPECIFICATION TO SEE WHAT IS THE 80% vs 100% CREDIT SOLUTION
private static void printHistogram( HashMap<String,Integer> hm )
{
List <String> keys = new ArrayList<String> (hm.keySet());
Collections.sort(keys);
for (String key: keys)
{
System.out.println(key + "\t" + hm.get(key));
}
}
}// END LAB8 CLASS
Here is the sample text file:
Brisbane
03163012
Australia
Tokyo
041022200
Japan
now I want to read three data together then put in different variables. Then take another three and so on.
location = brisbane;
phoneNumber = 03163012;
country = Australia;
Afterwards, passed into the constructor.
And there is a MAXIMUM LOCATION = 10 that have to be read
public boolean data()
{
boolean isValid = true;
boolean check = true;
int a = 0;
try
{
BufferedReader reader = new BufferedReader(newFileReader("location.txt"));
String data = reader.readLine();
while (data != null && check)
{
if (a != MAX_NUMBER)
{
for (int i = 0; i < 3; i++)
{
?????????
locations.add(newLocation);
a++;
}
else
check = false;
data =reader.readLine;
}
}
reader.close();
}
Can anyone help me with this one. I dont know what should I write in ????
thanks in advance
You probably want something like this inside your for loop:
locations.add(data);
data = reader.readLine();
if(data!=null)
phoneNumber.add(data);
else
break;
data = reader.readLine();
if(data!=null)
country.add(data);
else
break;
a++;
You want to read 3 lines, and add to locations, then phoneNumber, then country. There's all kinds of other problems with your code though (like a misplaced } and newFileReader)
Use Guava's method that reads file by lines and gives output as List<String>
Files.readLines(java.io.File, java.nio.charset.Charset)
Using it will make your code look much simplier, you will get rid of all those try-catch-finally and file buffers.
Iterate that list and use those strings as variables for:
location = brisbane;
phoneNumber = 03163012;
country = Australia;
iterating can look like this:
public static void main(String[] args) {
//it's you a mock
List<String> lines = new ArrayList<String>();
lines.add("a");
lines.add("1");
lines.add("aa");
lines.add("b");
lines.add("2");
lines.add("bb");
//Iterating String from file.
for (int i = 0; i < lines.size(); i += 3) {
String location = lines.get(i);
String phoneNumber = lines.get(i + 1);
String country = lines.get(i + 2);
//somehow use red variables
System.out.println(location);
System.out.println(phoneNumber);
System.out.println(country);
}
}
Note that in code above I filled my list, yours fill be filled after reading file.
What you need is another object for location, so you can store your values like this:
String data = reader.readLine();
int counter = 0;
MyLocation newLocation = null;
while (data != null && ((counter/3) != MAX_NUMBER)){
switch(counter % 3){
case 0:
newLocation = new MyLocation();
newLocation.setLocation(data);
break;
case 1:
newLocation.setPhone(data);
break;
case 2:
newLocation.setCountry(data);
locations.add(newLocation);
newLocation = null;
break;
}
counter++;
}
if(null != newLocation){
//Error management
}
The MyLocation class will look like this:
private String location = null;
private String phone = null;
private String country = null;
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
The code I've currently created stores the first line of the text file, creates a new Vehicle object and puts it in the array at the first position of null, and stores the same line in every null value in the array. I need it to be able to:
Store the contents of the first line, then store a new Vehicle object in the first place in the array that is null. Then repeat until there are no more lines.
I believe it is a problem with my for loop.
Note - I am required to use Array instead of ArrayList
public void addVehicle(Vehicle[] Honda) throws FileNotFoundException
{
if(canAddVehicle() == true)
{
for(int i = 0; i < vehicles.length; i++)
{
if(vehicles[i] == null)
{
Scanner reader = new Scanner(file);
Honda[i] = new Vehicle();
Honda[i].readRecord(reader);
vehicles[i] = Honda[i];
reader.close();
}
}
System.out.println("Vehicle Added!");
}
else
{
System.out.println("You can not add more than 4 vehicles.");
}
}
Vehicle class:
public void readRecord(Scanner reader)
{
setMake(reader.next());
setModel(reader.next());
setYear(reader.nextInt());
setvin(reader.next());
setValue(reader.nextDouble());
setMilesDriven(reader.nextInt());
setLastOilChange(reader.nextInt());
}
Data file:
Hyundai Sonata 2010 ABC236347NM2N2NW2 18455.34 8765 7567
Chevy Blazer 1998 1234H32343LMN3423 29556.65 38559 38559
//EDIT\
Constraits: I cannot create any new public methods or constructors, and I cannot have any additional class level data
You're looping within the readRecord method, even though that's meant to only store one object, isn't it?
It's possible that you can just remove the while loop - although that then relies on the addVehicle caller knowing how many entries are in the file.
It seems more likely that you should have a method to read everything from a file, populating a List<Vehicle> and returning it. For example:
public List<Vehicle> readVehicles(String file)
{
Scanner reader = new Scanner(file);
List<Vehicle> vehicles = new ArrayList<Vehicle>();
try
{
while (reader.hasNextLine())
{
vehicles.add(Vehicle.readFromScanner(reader));
}
}
finally
{
reader.close();
}
return vehicles;
}
// In vehicle
public static Vehicle readFromScanner(Scanner scanner)
{
String make = reader.next();
String model = reader.next();
int year = reader.nextInt();
String vin = reader.next();
// Don't use double for currency values
BigDecimal value = reader.nextBigDecimal();
int milesDriven = reader.nextInt();
// Shouldn't this be some sort of date type?
int lastOilChange = reader.nextInt();
// I'll assume you have a constructor like this
return new Vehicle(make, model, year, vin, value, milesDriven,
lastOilChange);
}
Found my solution!
public boolean addVehicle(Vehicle[] Honda) throws FileNotFoundException
{
boolean found = false;
int position = 0;
if(canAddVehicle() == true)
{
for(int i = 0; i < vehicles.length && !found; i++)
{
if(vehicles[i] == null)
{
position = i;
found = true;
}
}
Scanner reader = new Scanner(file);
while(reader.hasNext())
{
Honda[position] = new Vehicle();
Honda[position].readRecord(reader);
vehicles[position] = Honda[position];
position++;
}
reader.close();
return true;
}
return false;
}
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();
}
}
}
}