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
Related
How do I split a file input text into 2 different array? I want to make n array for the names, and an array for the phone numbers. I managed to do the file input, but ive tried everything and cant seem to split the names and the numbers, then put it into 2 different arrays. Im noob pls help
here is how the phonebook.txt file looks like
Bin Arry,1110001111
Alex Cadel,8943257000
Poh Caimon,3247129843
Diego Amezquita,1001010000
Tai Mai Shu,7776665555
Yo Madow,1110002233
Caup Sul,5252521551
This Guy,7776663333
Me And I,0009991221
Justin Thyme,1113332222
Hey Oh,3939399339
Free Man,4533819911
Peter Piper,6480013966
William Mulock,9059671045
below is my code
import java.io.*;
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class demos {
public static void main(String[] args){
FileInputStream Phonebook;
DataInputStream In;
int i = 0;
String fileInput;
try
{
Phonebook = new FileInputStream("phonebook.txt");
FileReader fr = new FileReader("phonebook.txt");
BufferedReader br = new BufferedReader(fr);
String buffer;
String fulltext="";
while ((buffer = br.readLine()) != null) {
fulltext += buffer;
// System.out.println(buffer);
String names = buffer;
char [] Y ;
Y = names.toCharArray();
System.out.println(Y);
}}
catch (FileNotFoundException e)
{
System.out.println("Error - this file does not exist");
}
catch (IOException e)
{
System.out.println("error=" + e.toString() );
}
For a full functionnal (rather than imperative) solution I propose you this one :
public static void main(String[] args) throws IOException {
Object[] names = Files.lines(new File("phonebook.txt").toPath()).map(l -> l.split(",")[0]).toArray();
Object[] numbers = Files.lines(new File("phonebook.txt").toPath()).map(l -> l.split(",")[1]).toArray();
System.out.println("names in the file are : ");
Arrays.stream(names).forEach(System.out::println);
System.out.println("numbers in the file are : ");
Arrays.stream(numbers).forEach(System.out::println);
}
output
names in the file are :
Bin Arry
Alex Cadel
Poh Caimon
Diego Amezquita
Tai Mai Shu
Yo Madow
Caup Sul
This Guy
Me And I
Justin Thyme
Hey Oh
Free Man
Peter Piper
William Mulock
numbers in the file are :
1110001111
8943257000
3247129843
1001010000
7776665555
1110002233
5252521551
7776663333
0009991221
1113332222
3939399339
4533819911
6480013966
9059671045
As you can see functionnal programming is short and smart …. and easy when you're accustomed
You could simplify it if you are using Java 8:
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
public class Test {
static ArrayList<String> names = new ArrayList<String>();
static ArrayList<String> numbers = new ArrayList<String>();
/**
* For each line, split it on the comma and send to splitNameAndNum()
*/
public static void main(String[] args) throws IOException {
Files.lines(new File("L:\\phonebook.txt").toPath())
.forEach(l -> splitNameAndNum(l.split(",")));
}
/**
* Accept an array of length 2 and put in the proper ArrayList
*/
public static void splitNameAndNum(String[] arr) {
names.add(arr[0]);
numbers.add(arr[1]);
}
}
And in Java 7:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Test {
static ArrayList<String> names = new ArrayList<String>();
static ArrayList<String> numbers = new ArrayList<String>();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("L:\\phonebook.txt")));
String line;
while ((line = br.readLine()) != null) {
splitNameAndNum(line.split(","));
}
}
/**
* Accept an array of length 2 and put in the proper ArrayList
*/
public static void splitNameAndNum(String[] arr) {
names.add(arr[0]);
numbers.add(arr[1]);
}
}
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.
So the code below finds words in a document as specific by the word input. Counts the number of times the words occurs in each sentence then stores that count in the arraylists at the bottom label a for cone and b for ctwo.
I want to use the arraylists in another class but can't seem to find a way to do it.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class exc {
public exc() {
}
public static void main(String[] args) throws Exception {
cone aa = new cone();
ctwo bb = new ctwo();
// after this I'm stuck
}
}
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Arrays;
import java.util.List;
public class cone {
public void cone() throws Exception {
BufferedReader e = new BufferedReader(new FileReader("words to be read.txt"));
String o;
while((o = e.readLine()) != null){
String[] sentences = o.split("\\b[.!?]\\s+");
//System.out.println(o);
String [] h = sentences;
{
BufferedReader t = new BufferedReader(new FileReader("Text to be scan.txt"));
String g;
while((g = t.readLine()) != null){
String[] set=g.split(" ");
List<String> list = Arrays.asList(set);
// System.out.println(Arrays.toString(set));
//System.out.println(o);
int sentenceNumb=1;
for (String sentence: h) {
int counter=0;
String[] words = sentence.replace(".", "").split(" ");
for(String word: words) {
if (list.contains(word)) {
counter++;
}
}
List<Integer> A = Arrays.asList(counter++);
}
}
}
}
}
}
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Arrays;
import java.util.List;
public class ctwo {
public void ctwo() throws Exception {
BufferedReader e = new BufferedReader(new FileReader("words to be read.txt"));
String o;
while((o = e.readLine()) != null){
String[] sentences = o.split("\\b[.!?]\\s+");
//System.out.println(o);
String [] h = sentences;
{
BufferedReader t = new BufferedReader(new FileReader("Text to be scan.txt"));
String g;
while((g = t.readLine()) != null){
String[] set=g.split(" ");
List<String> list = Arrays.asList(set);
// System.out.println(Arrays.toString(set));
//System.out.println(o);
int sentenceNumb=1;
for (String sentence: h) {
int counter=0;
String[] words = sentence.replace(".", "").split(" ");
for(String word: words) {
if (list.contains(word)) {
counter++;
}
}
List<Integer> B= Arrays.asList(counter++);
}
}
}
}
}
}
Best approach: You have both the ArrayLists in main(), pass them as function parameters to functions(from any class) that need them.
Not so good approach: Store the ArrayLists as package protected static class variables in the cone and ctwo classes. You can access them as cone.A and ctwo.B.
Pass the same array list in the constructor of both the classes.
your program seems weird.
I would suggest reading words and adding distinct words to hashmap with key as word and value as it's count.
i had a notepad file with
tea--10.00
coffee--20.00
bread--30.00.how to seperate tea,coffee,bread strings to an arrayList and seperate ineger values and storing to another variables.i need to program in java.i programmed like this
package sample_god1;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class filedata_retive_seperateVlaues
{
public static void main(String[] args) throws IOException
{
int var;
String var2;
Scanner sc=new Scanner(new File("222.txt"));
while(sc.hasNextLine())
{
String[] mnu=sc.nextLine().split("--");
int[] nums=new int[mnu.length];
for(int i=0;i<nums.length;i++)
{
System.out.println(var[i]);
}
}
}
}
List<String> items = new ArrayList<>();
List<Double> prices = new ArrayList<>();
while(sc.hasNextLine())
{
String[] mnu=sc.nextLine().split("--");
int[] nums=new int[mnu.length];
for(int i=0;i<nums.length;i++)
{
items.add(mnu[0]);
prices.add(Double.parseDouble(mnu[1]));
}
}
Instead of two separate list you should have a map ,
map.put(mnu[0],Double.parseDouble(mnu[1]));
Im trying to a specific String of number in a csv file and I keep getting an a FileNotFound exception even though the files exists. I cant seem to fix the problem
Sample Csv file
12141895, LM051
12148963, Lm402
12418954, Lm876
User Input : 12141895
Desired Result : True
import javax.swing.*;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import javax.swing.*;
import java.io.*;
import java.awt.*;
import java.awt.List;
public class tester
{
public static void main (String [] args ) throws IOException
{
boolean cool = checkValidID();
System.out.println(cool);
}
public static boolean checkValidID() throws IOException
{
boolean results = false;
Scanner scan = new Scanner(new File("C:\\Users\\Packard Bell\\Desktop\\ProjectOOD\\IDandCourse.csv"));
String s;
int indexfound=-1;
String words[] = new String[500];
String word = JOptionPane.showInputDialog("Enter your student ID");
while (scan.hasNextLine())
{
s = scan.nextLine();
if(s.indexOf(word)>-1)
indexfound++;
}
if (indexfound>-1)
{
results = true;
}
else
{
results = true;
}
return results;
}
}
use:
import java.io.File;
import java.io.FileNotFoundException;
Also, in your function declaration try using
public static boolean checkValidID() throws FileNotFoundException
and likewise with the main function.
If the file is present and named correctly, this should handle it.