Question: I have hashmap method that read .txt file and count Ship,TaxPay,credit words how many times they appeared. the problem is the count number is incorrect.

I have hashmap method that read .txt file and count "Ship","TaxPay","credit" words how many times they appeared. the problem is the count number is incorrect.

This is the pay.txt file

Ship TaxPay Ship TaxPay Ship TaxPay Ship TaxPay credit Ship credit Ship credit Ship Ship

This is my code:

public class calculatecount {

public static void main(String[] args) throws IOException {

for(String i: readFile().keySet()) {

System.out.println("Key: "+i+" Value: "+readFile().get(i));

}

}

public static HashMap readFile() throws IOException{

int count=0;

File file=new File("/Users/Desktop/pay.txt");

BufferedReader br = new BufferedReader(new FileReader(file));

HashMap ct=new HashMap ();

String st;

String []myList= {"Ship","TaxPay","credit"};

while((st=br.readLine())!=null) {

for(int i=0;i

Pattern pre=Pattern.compile(myList[i]);

Matcher prec=pre.matcher(st);

if(prec.find()) {

ct.put(myList[i], count++);

}

}

}

return ct;

}

}

The out put is:

Key: TaxPay Value: 7

Key: Ship Value: 14

Key: credit Value: 12

But it should be:

Key: TaxPay Value: 4

Key: Ship Value: 8

Key: credit Value: 3

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!