I am trying to read and process several languages' dictionaries in Java. So how can I arrange my code according to that? Thanks.
To turn them uppercase, I used this:
String str_uc=str.toUpperCase(Locale.ENGLISH);
But it's not supported for other languages, I am trying to read.
However, the main issue is that I can't read files in other languages properly before I turned them into uppercase.
Here's what I have done so far. Works perfect for English dictionary.
import java.util.ArrayList;
import java.util.Locale;
import java.io.*;
public class XmlCreating {
static ArrayList<Character> keywordletters = new ArrayList<Character>();
static ArrayList<Character> wordletters = new ArrayList<Character>();
static ArrayList<String> threeletter = new ArrayList<String>();
static ArrayList<String> fourletter = new ArrayList<String>();
static ArrayList<String> fiveletter = new ArrayList<String>();
static ArrayList<String> sixletter = new ArrayList<String>();
static ArrayList<String> sevenletter = new ArrayList<String>();
static ArrayList<String> words = new ArrayList<String>();
static ArrayList<String> allletters = new ArrayList<String>();
public static boolean hasApostrophe(String line){
for(int i=0; i<line.length();i++) {
if(line.charAt(i)=='\'' || line.charAt(i)=='-' )
return false;
}
return true;
}
public static void findLetters(String word, ArrayList<Character> ary) {
for(int i=0; i<word.length(); i++) {
ary.add(word.charAt(i));
}
}
public static boolean consistLetters(String keyword,String word) {
keywordletters.clear();
wordletters.clear();
findLetters(keyword,keywordletters);
findLetters(word,wordletters);
boolean found = false;
for(int i=0; i<wordletters.size(); i++) {
found=false;
for(int j=0; j<keywordletters.size(); j++) {
if(keywordletters.get(j)!='\''){
if(wordletters.get(i)==keywordletters.get(j)) {
keywordletters.set(j,'\'');
found=true;
break;
}
}
}
if(found!=true)
return false;
}
return found;
}
public static void findWords(String keyword){
words.clear();
for(int i=0; i<threeletter.size(); i++)
{
if(consistLetters(keyword,threeletter.get(i))==true)
words.add(threeletter.get(i));
}
for(int i=0; i<fourletter.size(); i++){
if(consistLetters(keyword,fourletter.get(i))==true)
words.add(fourletter.get(i));
}
for(int i=0; i<fiveletter.size(); i++){
if(consistLetters(keyword,fiveletter.get(i))==true)
words.add(fiveletter.get(i));
}
for(int i=0; i<sixletter.size(); i++){
if(consistLetters(keyword,sixletter.get(i))==true)
words.add(sixletter.get(i));
}
for(int i=0; i<sevenletter.size(); i++){
if(consistLetters(keyword,sevenletter.get(i))==true)
words.add(sevenletter.get(i));
}
}
public static void main(String args[]) {
//Locale.setDefault(new Locale("tr","TR"));
try {
FileInputStream fstream1 = new FileInputStream("en-GB.dic");
DataInputStream in = new DataInputStream(fstream1);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String str;
while ((str = br.readLine()) != null) {
String str_uc=str.toUpperCase(Locale.ENGLISH);
if(hasApostrophe(str_uc)){
allletters.add(str_uc);
if(str.length()==3)
threeletter.add(str_uc);
else if(str.length()==4)
fourletter.add(str_uc);
else if(str.length()==5)
fiveletter.add(str_uc);
else if(str.length()==6)
sixletter.add(str_uc);
else if(str.length()==7)
sevenletter.add(str_uc);
}
}
in.close();
}
catch (Exception e) {
System.err.println(e);
}
System.out.println(sevenletter.size());
System.out.println(sixletter.size());
System.out.println(fiveletter.size());
System.out.println(allletters.size());
int noOfXml=(int)(sevenletter.size()/10);
int lastXml=(int)(sevenletter.size()%10);
try{
int a=0;
int b=10;
for(int x=1;x<noOfXml+1;x++) {
FileWriter fstream2 = new FileWriter(x+".xml");
BufferedWriter out = new BufferedWriter(fstream2);
out.write("<?xml version='1.0' encoding='utf-8' ?><dictionary>");
for(int i=a;i<b;i++) {
findWords(sevenletter.get(i));
out.write("<ltr s='"+sevenletter.get(i)+"' w=");
for(int j=0; j<words.size();j++) {
out.write("'"+words.get(j)+"'");
if(j<words.size()-1)
out.write(";");
}
out.write("/>");
}
a=b;
b=b+10;
out.write("</dictionary>");
//Close the output stream
out.close();
}}catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
//for last five keywords
if(lastXml!=0) {
try{
FileWriter fstream3 = new FileWriter((noOfXml+1)+".xml");
BufferedWriter out1 = new BufferedWriter(fstream3);
out1.write("<?xml version='1.0' encoding='utf-8' ?><dictionary>");
for(int i=sevenletter.size()-lastXml;i<sevenletter.size();i++) {
findWords(sevenletter.get(i));
out1.write("<ltr s='"+sevenletter.get(i)+"' w=");
for(int j=0; j<words.size();j++) {
out1.write("'"+words.get(j)+"'");
if(j<words.size()-1)
out1.write(";");
}
out1.write("/>");
}
out1.write("</dictionary>");
//Close the output stream
out1.close();
}
catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
}
}//main
}//class
I encode each file as UTF-8
I would read each dictionary into a Set<String> possibly a NavigableSet<String> for each langage and I would place these is a Map keyed by the language.
Another way is to use words as key in a Map:
HashMap<(String) word ,Set<(String) codeLanguage>>
and, as Peter Lawrey sed, in this same Map
<(String) codeLanguage, Set(String) allLanguageWorld>>
If you use oriental language, you have to use Unicode.
Related
I am writing a java problem for converting the string with the "qwe" result.
Basically, the program requires to create a txt file with some words. Then, the program will read the words in txt and generate the words with qwe repeatedly.
If the words is abcdefg, the expected result should be qweqweq.
Can anyone help me?
import java.io.*;
public class Assignment2_1 {
static String[] readInputFile(String filename) {
int totalLines = 0;
try {
String thisLine;
BufferedReader reader = new BufferedReader(new FileReader(filename));
while ((thisLine = reader.readLine()) !=null){
totalLines++;
}
reader.close();
} catch (Exception e) {
System.out.println("File problem with" +filename);
System.exit(0);
}
String[] strArray = new String[totalLines];
try {
BufferedReader reader = new BufferedReader(new
FileReader(filename));
for (int i=0; i < totalLines; i++) {
strArray[i] = reader.readLine();
}
reader.close();
} catch (Exception e) {
System.out.println("File problem with" +filename);
System.exit(0);
}
return strArray;
}
public static void main(String[] args)
{
if (args.length != 1) {
System.out.println("Please provide a filename!\n");
System.exit(0);
}
String[] strArray = {"q","w","e"};
for (int i = 0; i <strArray.length; i++) {
System.out.println(strArray[i]);
}
}
}
You never call readInputFile(String) method in main(String[]) method.
You can try to use this code:
public static void main(String[] args){
if (args.length != 1) {
System.out.println("Please provide a filename!\n");
System.exit(0);
}
String[] lines=readInputFile(args[0]);
String[] strArray={"q","w","e"};
int count=0;
for(int i=0;i<lines.length;i++){
for(int j=0;j<lines[i].length();j++){
System.out.print(strArray[count%3]);
count++;
}
System.out.print("\r\n");
}
}
You can use Stream API too.
static String[] strArray={"q","w","e"};
int count=0;
public static void main(String[] args){
if (args.length != 1) {
System.out.println("Please provide a filename!\n");
System.exit(0);
}
String[] lines=readInputFile(args[0]);
Stream.of(lines).forEach(s->{
for(int j=0;j<s.length();j++){
System.out.print(strArray[count%3]);
count++;
}
System.out.print("\r\n");
}
}
I want to create a multidimensional array and pass it as a parameter in a method and then fill the arrayList with elements and return the new version of the arrayList to be able to use that array in different classes but I get java.lang.NoSuchMethodError: I think the problem is about the way i return the array. I searched but I could not find . How can I do it correctly?
here is my code;
public test{
public static List<List<String>> 2Darray=new ArrayList<List<String>>(); // TE ERROR IN THIS LINE
public List<List<String>> fillArray(List<List<String>> array){
BufferedReader in = null;
ArrayList<String> row = new ArrayList<String>();
try {
in = new BufferedReader(new FileReader("sampleFile.txt"));
String read = null;
while ((read = in.readLine()) != null) {
String[] splited = read.split("\\s+");
for(int i=0; i<splited.length ; i++){
row.add(splited[i]);
}
array.add(row);
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
}
return array;
}
A little tinkering (just getting it to compile) results in this which seems not to have a problem. Perhaps your issue is elsewhere.
public List<List<String>> fillArray(List<List<String>> array) {
BufferedReader in = null;
ArrayList<String> row = new ArrayList<String>();
try {
in = new BufferedReader(new FileReader("sampleFile.txt"));
String read = null;
while ((read = in.readLine()) != null) {
String[] splited = read.split("\\s+");
for (int i = 0; i < splited.length; i++) {
row.add(splited[i]);
}
array.add(row);
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return array;
}
BTW: You should really use try with resources - it is much clearer.
Modified your code a bit so that it compiled, and replaced the reading from a text file to reading a string. There were several issues, but it seems to work. Give it a try.
The main problems I noticed were mismatching curly braces, and starting a variable name with a number.
import java.util.*;
import java.io.*;
public class Main {
public static List<List<String>> array2D = new ArrayList<List<String>>();
public List<List<String>> fillArray(List<List<String>> array) {
BufferedReader in = null;
ArrayList<String> row = new ArrayList<String>();
try {
String str = "Some test text";
InputStream is = new ByteArrayInputStream(str.getBytes());
//in = new BufferedReader(new FileReader("sampleFile.txt"));
in = new BufferedReader(new InputStreamReader(is));
String read = null;
while ((read = in.readLine()) != null) {
String[] splited = read.split("\\s+");
for(int i=0; i<splited.length ; i++) {
row.add(splited[i]);
}
array.add(row);
}
}
catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
}
finally {
try {
in.close();
}
catch (IOException e) {
}
}
return array;
}
public static void main(String[] args) {
Main main = new Main();
List<List<String>> test = main.fillArray(array2D);
for(int i = 0; i < test.size(); i++) {
for(int j = 0; j < test.get(i).size(); j++) {
System.out.println(test.get(i).get(j));
}
}
}
}
So here I have code I have HashMap made up by the words in file, I am adding words and writing them on file and it works, but when I use my remove function for some reaseon doesnt do anything here is the code :
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static File file = new File( C:\\Users\\N\\Desktop\\Newfolder\\Dictionary\\src\\nmishewa\\geekycamp\\dictionary\\bg_win1251.txt");
public static int value = 1;
private static Scanner input;
public static Scanner in = new Scanner(System.in);
public static Map<String, Integer> map = new HashMap<String, Integer>();
public static void main(String[] args) throws FileNotFoundException {
readFile();
System.out.println("Enter number of function wanted" + "\n1 to add"
+ "\n2 for searching by prefix" + "\n3 for deleting");
int choice = in.nextInt();
if (choice == 1) {
System.out.println("enter words seprated by comma");
String wd = in.next();
add(wd);
}
if (choice == 2) {
System.out.println("Enter prefix");
String wd = in.next();
prefixSearch(wd);
}
if (choice == 3) {
System.out.println("ENTER word to delete");
String wd = in.next();
remove(wd);
}
}
public static void readFile() throws FileNotFoundException {
input = new Scanner(file);
boolean done = false;
int value = 1;
while (input.hasNext()) {
String word = input.next().toLowerCase();
String[] line = word.split("[,\\s]+");
for (int j = 0; j < line.length; j++) {
map.put(line[j], value);
value++;
done = true;
}
}
if (done == true) {
System.out.println("Succes");
}
}
public static void prefixSearch(String wd) {
System.out.println("Enter prefix");
String prefix = wd.toLowerCase();
for (Map.Entry<String, Integer> key : map.entrySet()) {
if (key.getKey().startsWith(prefix)) {
System.out.println(key.getKey());
}
}
}
public static void add(String wd) {
boolean done = false;
String word = wd.toLowerCase();
String[] line = word.split("[,\\s]+");
for (int j = 0; j < line.length; j++) {
if (!map.containsKey(line[j])) {
map.put(line[j], value);
value++;
try {
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(map.toString());
bw.close();
done = true;
} catch (Exception e) {
e.printStackTrace();
}
} else {
continue;
}
}
if (done == true) {
System.out.println("Success");
}
}
public static void remove(String wd) {
boolean done = false;
String word = wd.toLowerCase();
String[] line = word.split("[,\\s]+");
for (int j = 0; j < line.length; j++) {
for (Map.Entry<String, Integer> key : map.entrySet()) {
if (key.getKey().equals(line[j])) {
map.remove(key.getKey(), key.getValue());
try {
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(map.toString());
bw.close();
done = true;
} catch (Exception e) {
e.printStackTrace();
}
} else {
continue;
}
}
}
if (done == true) {
System.out.println("Succes");
}
}
}
Every other method is working just fine, but remove. Is there something wrong with the loops, maybe use more optimal way or?
The reason for failure is that you're trying to change the map while iterating the entries. As with any collection - if you try to modify it while iterating it you'll get ConcurrentModificationException.
Further, there's a redundant inner for-loop (redundant because the whole purpose of a map is that you won't have to iterate it when you're looking for a specific value/s) which means that you'll try to override the file many times when only once is sufficient.
public static void remove(String wd) {
boolean done = false;
String word = wd.toLowerCase();
String[] line = word.split("[,\\s]+");
for (int j = 0; j < line.length; j++) {
map.remove(line[j]);
}
try {
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(map.toString());
bw.close();
done = true;
} catch (Exception e) {
e.printStackTrace();
}
if (done == true) {
System.out.println("Success");
}
}
The issues that I can see in your code are the following:
You forgot a quote when defining the file:
public static File file = new File( C:\\Users\\N\\Desktop\\Newfolder\\Dictionary\\src\\nmishewa\\geekycamp\\dictionary\\bg_win1251.txt")
should be:
public static File file = new File("C:\\Users\\N\\Desktop\\Newfolder\\Dictionary\\src\\nmishewa\\geekycamp\\dictionary\\bg_win1251.txt");
The remove() function in a map receives only one parameter, which is the key of the entry you want to remove, so:
map.remove(key.getKey(), key.getValue());
should be:
map.remove(key.getKey());
Also, since your getting the entrySet of your map, maybe you should consider renaming the key variable in the rename() function to entry.
A simple data file which contains
1908,Souths,Easts,Souths,Cumberland,Y,14,12,4000
1909,Souths,Balmain,Souths,Wests,N
Each line represents a season of premiership and has the following format: year, premiers, runners up, minor premiers, wooden spooners, Grand Final held, winning score,
losing score, crowd
I know how to store a data into an array and use the delimiter, but I am not exactly sure how to store EACH data item by a comma into separate arrays? Some suggestions and what particular code to be used would be nice.
UPDATE:
I just added the code but it still didn't work. Here's the code:
import java.io.*;
import java.util.Scanner;
public class GrandFinal {
public static Scanner file;
public static String[] array = new String[1000];
public static void main(String[] args) throws FileNotFoundException {
File myfile = new File("NRLdata.txt");
file = new Scanner (myfile);
Scanner s = file.useDelimiter(",");
int i = 0;
while (s.hasNext()) {
i++;
array[i] = s.next();
}
for(int j=0; j<array.length; j++) {
if(array[j] == null)
;
else if(array[j].contains("Y"))
System.out.println(array[j] + " ");
}
}
}
Here you go. Use ArrayList. Its dynamic and convenient.
BufferedReader br = null;
ArrayList<String> al = new ArrayList();
String line = "";
try {
br = new BufferedReader(new FileReader("NRLdata.txt"));
while ((line = br.readLine()) != null) {
al.add(line);
}
} catch (Exception e) {
e.printStackTrace();
}
for (int i = 0; i < al.size(); i++) {
System.out.println(al.get(i));
}
What does not work in your case ?
Because your season array is empty. You need to define the length, for ex:
private static String[] season = new String[5];
This is not right because you don't know how many lines you are going to store. Which is why I suggested you to Use ArrayList.
After working around a bit, I have come up with following code:
private static File file;
private static BufferedReader counterReader = null;
private static BufferedReader fileReader = null;
public static void main(String[] args) {
try {
file = new File("C:\\Users\\rohitd\\Desktop\\NRLdata.txt");
counterReader = new BufferedReader(new FileReader(file));
int numberOfLine = 0;
String line = null;
try {
while ((line = counterReader.readLine()) != null) {
numberOfLine++;
}
String[][] storeAnswer = new String[9][numberOfLine];
int counter = 0;
fileReader = new BufferedReader(new FileReader(file));
while ((line = fileReader.readLine()) != null) {
String[] temp = line.split(",");
for (int j = 0; j < temp.length; j++) {
storeAnswer[j][counter] = temp[j];
System.out.println(storeAnswer[j][counter]);
}
counter++;
}
} catch (IOException e) {
e.printStackTrace();
}
}
catch (FileNotFoundException e) {
System.out.println("Unable to read file");
}
}
I have added counterReader and fileReader; which are used for counting number of lines and then reading the actual lines. The storeAnswer 2d array contains the information you need.
I hope the answer is better now.
I am trying to create a 2d array using the contents of a text file, however I am unable to return it. It says it cannot find the symbol firstDimension, however I declared it within the method.
import java.io.*;
import java.util.*;
public class Map {
public static char[][] readFile() {
try {
List<String> list = new ArrayList<String>();
String thisLine = null;
BufferedReader br;
br = new BufferedReader(new FileReader("map.txt"));
while ((thisLine = br.readLine()) != null) {
list.add(thisLine);
}
char[][] firstDimension = new char[list.size()][];
for (int i = 0; i < list.size(); i++) {
firstDimension[i] = list.get(i).toCharArray();
}
for (int i=0; i < firstDimension.length; i++) {
for (int j=0; j < firstDimension[i].length; j++) {
System.out.print(firstDimension[i][j]);
}
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
}
return firstDimension;
}
}
firstDimension is declared within your try block hence its scope is that try block. to be able to return it outside the try block, you need to declare it as follows:
public static char[][] readFile() {
char[][] firstDimension = null;
try {
List<String> list = new ArrayList<String>();
String thisLine = null;
BufferedReader br;
br = new BufferedReader(new FileReader("map.txt"));
while ((thisLine = br.readLine()) != null) {
list.add(thisLine);
}
firstDimension = new char[list.size()][];
for (int i = 0; i < list.size(); i++) {
firstDimension[i] = list.get(i).toCharArray();
}
for (int i=0; i < firstDimension.length; i++) {
for (int j=0; j < firstDimension[i].length; j++) {
System.out.print(firstDimension[i][j]);
}
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
}
return firstDimension;
}
In that case, if an exception is encountered, your method could return null.
This is another example of the same issue.