Counting instances of letter sequences - java

The purpose of this code is to count the instances of letters that occur in sequence, using HashMaps, and Streams.
I've run into the problem of my System.out.print(results) is printing [is=3, imple=2, it=1] to the console, but my junit is saying "expected <[is=3 imple =2 it=1]> but was <[]>.
The code prints out [is=3, imple=2, it=1] but it doesn't seem to actually be updating this out into memory. Any tips or advice on what I should do?
Thank you so much!
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
public class WordCount {
protected Map<String, Integer> counts;
static Scanner in= new Scanner(System.in);
public WordCount(){
counts = new HashMap<String,Integer>();
}
public Map getCounts(){
return counts;
}
public int parse(Scanner in, Pattern pattern){
int counter=0;
while (in.hasNext()) {
// get the next token
String token = in.next();
// match the pattern within the token
Matcher matcher = pattern.matcher(token);
// process each match found in token (could be more than one)
while (matcher.find()) {
// get the String that matched the pattern
String s = matcher.group().trim();
// now do something with s
counter=counts.containsKey(s) ? counts.get(s):0;
counts.put(s,counter+1);
}
}
return counter;
}
public void report(PrintStream printstream){
List<Map.Entry<String, Integer>> results = new ArrayList<Map.Entry<String, Integer>>();
for(Map.Entry<String, Integer> entry: counts.entrySet()){
results.add(entry);
Collections.sort(results,Collections.reverseOrder(Map.Entry.comparingByValue()));
results.toString();
}
System.out.println(results); // The main problem is this outputs [is=3,
imple=2, it=1] but the junit doesn't pass.
}
}
//Test Cases
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Scanner;
import java.util.regex.Pattern;
import junit.framework.TestCase;
public class TestWordCount extends TestCase {
public void test_WordCount_parse() {
WordCount wc = new WordCount();
Scanner in = new Scanner("this is a simple test, but it is not simple to pass");
Pattern pattern = Pattern.compile("[i][a-z]+");
wc.parse(in, pattern);
assertEquals((Integer)3, wc.getCounts().get("is"));
assertEquals((Integer)2, wc.getCounts().get("imple"));
assertEquals((Integer)1, wc.getCounts().get("it"));
}
public void test_WordCount_report() {
WordCount wc = new WordCount();
Scanner in = new Scanner("this is a simple test, but it is not simple to pass");
Pattern pattern = Pattern.compile("[i][a-z]+");
wc.parse(in, pattern);
ByteArrayOutputStream output = new ByteArrayOutputStream();
wc.report(new PrintStream(output));
String out = output.toString();
String ls = System.lineSeparator();
assertEquals("is=3_imple=2_it=1_".replace("_", ls), out);
}

`public void report(PrintStream printstream)`
In this method you do not print anything to printstream. Try adding
printstream.print(results);
to this method.
Note that, although System.out is a PrintStream itself, it's a different stream that is bound to the console.

Related

How would I make a scanner anagram?

Essentially I need to create a anagram program to filter out the specific characters I input using a scanner from a dictionary file. Example, if I enter 'Stop' the result would be "tops spot pots" etc
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.util.stream.Stream;
public class Anagram1 {
public static void main(String[] args) throws IOException {
new Anagram1().doIt();
}
private void doIt() throws IOException {
Scanner scanner = new Scanner(System.in);
while (true) {
String theWord = scanner.next();
if (theWord.equals("999")) {
scanner.close();
break;
}
ISinglyLinkedList<String> anagrams = listAnagrams(theWord);
anagrams.forEach(System.out::print);
}
}
private ISinglyLinkedList<String> listAnagrams(final String theWord) throws
IOException {
Stream<String> dict = Files.lines(Paths.get("Data", "pocket.dic"));
ISinglyLinkedList<String> theList = dict
.collect(Util.toSinglyLinkedList())
//Add a filter and a forEach to print the specific words you wanna print
;
dict.close();
return theList;
}
}
So far the program only gives me enter code here every single word in the dictionary. Is there a way to filter out only the words that share the same letter?
You could use the fact that two words are anagrams if after sorting they are the same:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Anagram1 {
public static void main(String[] args) throws IOException {
Map<String, List<String>> anagramsMap = new HashMap<>();
try (Stream<String> dict = Files.lines(Paths.get("Data", "pocket.dic"))) {
dict.forEach(w -> anagramsMap.computeIfAbsent(getSortedWord(w), x -> new ArrayList<>()).add(w));
}
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Enter a word to get its anagrams or 999 to exit: ");
String word = scanner.next();
if (word.equals("999")) {
break;
}
List<String> anagrams = anagramsMap.get(getSortedWord(word.toLowerCase()));
System.out.println(String.join(" ", anagrams));
}
}
public static String getSortedWord(String word) {
return Stream.of(word.split("")).sorted().collect(Collectors.joining());
}
}
Example Usage:
Enter a word to get its anagrams or 999 to exit: Stop
post pots spot stop tops
Enter a word to get its anagrams or 999 to exit: 999

Calling method from different class (different than other questions)

So I'm relatively new to java and I'm trying to use a method from a different class inside my main.
The method I'm using to pull doesn't contain any data initially but pulls the data from a text doc.
I've included the code that calls the other class method that loads the data from the file. It sill doesn`t work, so where is my mistake?
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FinalRobert {
public static void main(String[] args) {
//output of animalList class here
}
Here is the class I'm trying to pull from:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
public class animalList {
public void animalDetails () {
int i = 0;
String animalInfo = "C:/Users/Robert/Documents/animals.txt";
String animalHabitat = "‪C:/Users/Robert/Documents/habitats.txt";
try {
File animalFile = new File(animalInfo);
FileReader animalReader = new FileReader(animalFile);
BufferedReader animalList = new BufferedReader (animalReader);
StringBuilder animalDetailList = new StringBuilder();
String line;
while ((line = animalList.readLine()) != null) {
for (i = 0; i <4 ; i++) {
System.out.println(line);
animalList.readLine();
}
}
animalReader.close();
System.out.println(animalDetailList.toString());
}
catch (IOException e) {
}
}
}
So I want to have the output of the animalList class in my main, but I don't know how to bring it over because I'm not necessarily bring over variable, but a process. The full thing should bring the first line and four past it (so a total of the first five lines in the doc). Hopefully that makes things easier to see my problem.
This is a mcve of AnimalList :
public class AnimalList {//use java naming convention
public void animalDetails () {
//mcve should be runnable. The problem you ask help with is not
//reading from file, so remove file reading functionality to make it mcve
StringBuilder animalDetailList = new StringBuilder();
animalDetailList.append("Family: Cats").append("\n")
.append("Type : Panther").append("\n")
.append("Weight: 250kg").append("\n")
.append("Color : Pink");
System.out.println(animalDetailList.toString());
}
}
Invoke its method from another class:
public class FinalRobert {
public static void main(String[] args) {
//to invoke animalDetails() method use
AnimalList aList = new AnimalList();
aList.animalDetails();
//if you do not need the aList refrence you could use
//new AnimalList().animalDetails();
}
}
Output
Family: Cats Type : Panther Weight: 250kg Color :
Pink
I hope this might help you.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FinalRobert {
public static void main(String[] args) {
animalList list = new animalList();
list.animalDetails();
}
}
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
public class animalList {
public String animalDetails () {
int i = 0;
String output="";
String animalInfo = "C:/Users/Robert/Documents/animals.txt";
String animalHabitat = "‪C:/Users/Robert/Documents/habitats.txt";
try {
File animalFile = new File(animalInfo);
FileReader animalReader = new FileReader(animalFile);
BufferedReader animalList = new BufferedReader (animalReader);
String line;
while ((line = animalList.readLine()) != null & i<4) {
System.out.println(line);
output = output + "\n"+ line;
i++;
}
animalReader.close();
System.out.println(output);
}
catch (IOException e) {
}
return output;
}
}

How to get values from grid using regex in java

I'm working on resume parser and i can get some of data i.e company details from text but not getting if it is kept in a grid or table
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JOptionPane;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
public class CmpnyNameex {
public static void main(String[] args)throws IOException {
String text="";
String name="";
XWPFDocument msDocx = new XWPFDocument(new FileInputStream("A:\\Resumes\\Anwesh.docx"));
XWPFWordExtractor extractor = new XWPFWordExtractor(msDocx);
text = extractor.getText();
}
catch(FileNotFoundException ex){ex.printStackTrace();
JOptionPane.showMessageDialog(null,"The system cannot find the file specified file it may be because of old file format","Error",JOptionPane.ERROR_MESSAGE);
}
String rx13="(?<=Have been associated with).*.(.*Ltd?)";
Pattern p1 = Pattern.compile(rx13);
Matcher found1 = p1.matcher(text);
while(found1.find())
{
name= found1.group(0);
}
}
}

Java - Zip Code Validator not working?

I'm having a few issues with my zip code validator which reads a text file with UK postcodes then returns true or false after validation.
Below is the section of code I'm having issues with particularly (ZipCodeValidator) which is public and should be declared in a file called ZipCodeValidator.java. And then (Zip) which cannot find symbol.
public class ZipCodeValidator {
private static String regex = "^[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}$";
private static Pattern pattern = Pattern.compile(regex);
public boolean isValid(String zipCode) {
Matcher matcher = pattern.matcher(zip);
return matcher.matches();
}
}
And below here is the entire program for reference. Any help is appreciated.
package postcodesort;
import java.util.*;
import java.util.Random;
import java.util.Queue;
import java.util.TreeSet;
import java.io.File;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
import java.util.StringTokenizer;
import java.util.zip.ZipFile;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PostCodeSort
{
Queue<String> postcodeStack = new LinkedList<String>();
public static void main(String[] args) throws IOException
{
FileReader fileReader = null;
ZipCodeValidator zipCodeValidator = new ZipCodeValidator();
// Create the FileReader object
try {
fileReader = new FileReader("postcodes1.txt");
BufferedReader br = new BufferedReader(fileReader);
String str;
while((str = br.readLine()) != null)
{
if(zipCodeValidator.isValid(str)){
System.out.println(str + " is valid");
}
else{
System.out.println(str + " is not valid");
}
}
}
catch (IOException ex)
{
// handle exception;
}
finally
{
fileReader.close();
}
}
}
public class ZipCodeValidator {
private static String regex = "^[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}$";
private static Pattern pattern = Pattern.compile(regex);
public boolean isValid(String zipCode) {
Matcher matcher = pattern.matcher(zip);
return matcher.matches();
}
}
Possibly a copy+paste issue, but Matcher matcher = pattern.matcher(zip); doesn't match the method parameter zipCode. Do you have zip defined somewhere else, and possibly validating against that?
It's when I added the read file code thats when the problems arose like the ones I specified above
Make sure you clean up the String before you pass it in. To remove any leading or trailing whitespace characters use
if(zipCodeValidator.isValid(str.strip())){
lastly, your regex only matches upper case. Make sure you allow all cases by using
str.strip().toUpperCase()
or changing your Regex:
private static Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);

Java - Merging two sets of code

I've written two separate pieces of code. Now I want to merge both pieces of code. Now one part opens a text file and displays the contents of the text file and the second piece of code validates manually entered postcodes. Now I want to read a text file and then automatically validate postcodes within the text file. Not sure how I can merge them. Any questions please ask as I'm stuck.
package postcodesort;
import java.util.*;
import java.util.Random;
import java.util.Queue;
import java.util.TreeSet;
import java.io.File;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
import java.util.StringTokenizer;
public class PostCodeSort
{
Queue<String> postcodeStack = new LinkedList<String>();
public static void main(String[] args) throws IOException
{
FileReader fileReader = null;
// Create the FileReader object
try {
fileReader = new FileReader("postcodes1.txt");
BufferedReader br = new BufferedReader(fileReader);
String str;
while((str = br.readLine()) != null)
{
System.out.println(str + "");
}
}
catch (IOException ex)
{
// handle exception;
}
finally
{
fileReader.close();
}
// Close the input
}
}
Second part that manually validates postcodes:
List<String> zips = new ArrayList<String>();
//Valid ZIP codes
zips.add("SW1W 0NY");
zips.add("PO16 7GZ");
zips.add("GU16 7HF");
zips.add("L1 8JQ");
//Invalid ZIP codes
zips.add("Z1A 0B1");
zips.add("A1A 0B11");
String regex = "^[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}$";
Pattern pattern = Pattern.compile(regex);
for (String zip : zips)
{
Matcher matcher = pattern.matcher(zip);
System.out.println(matcher.matches());
}
You should create a class called something like ZipCodeValidator that contains the functionality of your second snippet. It will look something like this
public class ZipCodeValidator {
private static String regex = "^[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}$";
private static Pattern pattern = Pattern.compile(regex);
public boolean isValid(String zipCode) {
Matcher matcher = pattern.matcher(zip);
return matcher.matches();
}
}
Then you can create an instance of this class
ZipCodeValidator zipCodeValidator = new ZipCodeValidator();
and then use it in your main method
boolean valid = zipCodeValidator.isValid(zipCode);
Merging your question and the answer by #hiflyer I posted this answer, this makes an assumption that the file postcodes1.txt has all the zip codes in separate lines.
package postcodesort;
import java.util.*;
import java.util.Random;
import java.util.Queue;
import java.util.TreeSet;
import java.io.File;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
import java.util.StringTokenizer;
public class PostCodeSort
{
Queue<String> postcodeStack = new LinkedList<String>();
public static void main(String[] args) throws IOException
{
FileReader fileReader = null;
ZipCodeValidator zipCodeValidator = new ZipCodeValidator();
// Create the FileReader object
try {
fileReader = new FileReader("postcodes1.txt");
BufferedReader br = new BufferedReader(fileReader);
String str;
while((str = br.readLine()) != null)
{
if(zipCodeValidator.isValid(str)){
System.out.println(str + " is valid");
}
else{
System.out.println(str + " is not valid");
}
}
}
catch (IOException ex)
{
// handle exception;
}
finally
{
fileReader.close();
}
}
}
public class ZipCodeValidator {
private static String regex = "^[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}$";
private static Pattern pattern = Pattern.compile(regex);
public boolean isValid(String zipCode) {
Matcher matcher = pattern.matcher(zip);
return matcher.matches();
}
}

Categories