Java removing from HashMap and writing changes in file - java

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.

Related

i create an algorithm and when i try to print it, bufferedWriter create an empty file

i made an algorithm to do a calculus. it works well but bufferedWriter creates an empty file. I tried every kind of solutions, but every time it creates an empty file. i need the file as txt. how to fix it?
to help you reading my code:
addressCalc() is a function that open a txt and upload in an hashmap the data
uniqueAddress() is a function that calculate how many unique address there are in my data
nftNumbers() is a function that calculate how many nfts has each address
calculus() is the function that i need to print in a txt the final result
package calculator.v2;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class AlgorithmV2 {
HashMap <Integer, String> listAddress;
HashMap <Integer, String> totalAddress;
HashMap <String, String> uniqueAddress;
HashMap <Integer, String> orderAddress;
HashMap <String, Float> nfts;
int totalNfts = 33;
float cifra;
String lucifer, astaroth, beelzebup;
public AlgorithmV2() {
super();
listAddress = new HashMap<Integer, String>();
totalAddress = new HashMap<Integer, String>();
uniqueAddress = new HashMap<String, String>();
orderAddress = new HashMap<Integer, String>();
nfts = new HashMap<String, Float>();
addressCalc();
uniqueAddress();
nftNumbers();
calculus();
}
public float getCifra() {
return cifra;
}
public void setCifra(float cifra) {
this.cifra = cifra;
}
public HashMap<Integer, String> getTotalAddress() {
return totalAddress;
}
public void setTotalAddress(HashMap<Integer, String> totalAddress) {
this.totalAddress = totalAddress;
}
public HashMap<String, String> getUniqueAddress() {
return uniqueAddress;
}
public void setUniqueAddress(HashMap<String, String> uniqueAddress) {
this.uniqueAddress = uniqueAddress;
}
public HashMap<Integer, String> getOrderAddress() {
return orderAddress;
}
public void setOrderAddress(HashMap<Integer, String> orderAddress) {
this.orderAddress = orderAddress;
}
public HashMap<String, Float> getNfts() {
return nfts;
}
public void setNfts(HashMap<String, Float> nfts) {
this.nfts = nfts;
}
public int getTotalNfts() {
return totalNfts;
}
public void setTotalNfts(int totalNfts) {
this.totalNfts = totalNfts;
}
public float addressCalc() {
try {
FileReader reader = new FileReader("src\\calculator\\data\\snapshot.txt");
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
Pattern addressPattern = Pattern.compile("stars+[A-Za-z0-9]+");
int i = 0;
while ((line = bufferedReader.readLine()) != null) {
Matcher address = addressPattern.matcher(line);
if(address.find()) {
listAddress.put(i, address.group(0));
i++;
}
}
reader.close();
return 1;
} catch (IOException e) {
e.printStackTrace();
return 0;
}
}
public void uniqueAddress(){
int temp = 0;
for(int i = 0; i < listAddress.size(); i++) {
if(uniqueAddress.get(listAddress.get(i)) == null) {
uniqueAddress.put(listAddress.get(i), listAddress.get(i));
orderAddress.put(temp, listAddress.get(i));
temp++;
}
}
}
public void nftNumbers() {
try {
FileReader reader = new FileReader("src\\calculator\\data\\data.txt");
BufferedReader bufferedReader = new BufferedReader(reader);
cifra = Float.parseFloat(bufferedReader.readLine());
lucifer = bufferedReader.readLine();
beelzebup = bufferedReader.readLine();
astaroth = bufferedReader.readLine();
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
float temp = 0;
int n;
for(int i=0; i < uniqueAddress.size(); i++) {
for(int j=0; j < listAddress.size(); j++) {
if(uniqueAddress.get(orderAddress.get(i)).equals(listAddress.get(j))) {
temp++;
}
}
if(temp >= 6) {
temp = temp + temp/3;
}
if(astaroth.equals(uniqueAddress.get(orderAddress.get(i))) || lucifer.equals(uniqueAddress.get(orderAddress.get(i))) || beelzebup.equals(uniqueAddress.get(orderAddress.get(i)))) {
temp += 11;
}
n = (int) temp;
totalNfts += n;
nfts.put(uniqueAddress.get(orderAddress.get(i)), temp);
temp = 0;
}
}
public void calculus() {
float temp = (float) 0;
try(FileWriter fw = new FileWriter("rewards.txt", true)){
BufferedWriter bw = new BufferedWriter(fw);
for(int i = 0; i < orderAddress.size(); i++) {
temp = nfts.get(orderAddress.get(i))/totalNfts*cifra;
System.out.println(orderAddress.get(i)+","+temp);
bw.write(orderAddress.get(i)+","+temp);
temp = 0;
}
bw.close();
}
catch(IOException e){
// handle the exception
}
}
}``
Maybe your code produces an exception before the file could be written. You could try the following to narrow down the problem (if you are not comfortable with using a debugger):
public void calculus() {
float temp = (float) 0;
String baseDir = "C:/Users/..../folder";
try(FileWriter fw = new FileWriter(baseDir + "rewards.txt", true)){
BufferedWriter bw = new BufferedWriter(fw);
// check if this string will be present in
// your file
bw.write("Test");
// this will force the BufferedWriter to
// write to the file immediately
bw.flush();
System.out.println("orderAddress.size() = " + orderAddress.size());
for(int i = 0; i < orderAddress.size(); i++) {
temp = nfts.get(orderAddress.get(i))/totalNfts*cifra;
System.out.println(orderAddress.get(i)+","+temp);
bw.write(orderAddress.get(i)+","+temp);
temp = 0;
// this will force the BufferedWriter to
// write to the file immediately
bw.flush();
}
bw.close();
}
catch(IOException e){
// 1
System.err.println(e);
// 2
throw new RuntimeException("IOException occurred" +
" while trying to write to file.", e);
}
}
I added some lines...
First, I added a new variable baseDir where you can set the path to the folder in which the file should be created.
bw.write("Test"); checks if "Test" will appear in your file. Then I added bw.flush(); twice. This force the BufferedWriter to immediately write to the file. If an exception occurred in the for-loop, your file will still contain the last working execution.
In the catch-block you should handle your exception in some way. I provided you with two of many other possibilities:
If you want your program to continue when an exception occurs, you can just print the exception to the console, so you would still be aware of it.
If you want your program to stop when an exception occurs, you can throw a RuntimeException

Java scanner returns unknown characters like ÿş

Hi I am trying to write a word counter class on Java. I suppose I am reading a file with scanner from the base folder and printing them to the console. However, first item of file returns with a prefix ÿş or sometimes ?? two question mark. Every item in files are string words. Here is my source code, I could not managed to handle this, so please any help would be appreciated, thanks... (By the way I am using JCreator LE 4.5)
import java.io.*;
import java.util.*;
public class WordCounter implements Comparator<Integer>{
public static Scanner myScanner;
private static int orderNumber = 0;
private static String inputName = "";
private static String outputName = "";
private static LinkedHashMap<String, Integer> dictionary = new LinkedHashMap<String, Integer>();
private static ArrayList<String> words = new ArrayList<String>();
private static SortedSet<String> keys;
private static Scanner in;
public static void main(String[] args) {
myScanner = new Scanner(System.in);
System.out.println("Please enter a file name to read...");
inputName = myScanner.nextLine();
System.out.println("Please enter a file name to write in...");
outputName = myScanner.nextLine();
askForOptions();
readFromFile(inputName);
writeToFile(outputName, orderNumber);
}
private static void readFromFile(String fileName){
try {
in = new Scanner(new File(fileName+".txt"));
while(in.hasNext()){
String lowered = in.next().toLowerCase();
if(!lowered.equals(" ") || !lowered.equals("") || !lowered.equals(null)){
System.out.println(lowered);
int lastInd = lowered.length()-1;
char lastChar = lowered.charAt((lastInd-1));
System.out.println(lastChar);
if (lastChar == '?' || lastChar == ',' || lastChar == '.'){
String newLowered = lowered.substring(0, (lastInd-1));
words.add(newLowered);
}else{
words.add(lowered);
}
}
}
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private static void writeToFile(String fileName, int orderNumber){
for(String word: words) {
if(dictionary.containsKey(word)){
int val = (int) dictionary.get(word);
dictionary.put(word, val+1);
}else{
dictionary.put(word, 1);
}
}
if(orderNumber == 1){
keys = new TreeSet<String>(dictionary.keySet());
try {
FileWriter writer = new FileWriter(fileName+".txt");
for(String key:keys){
writer.write(key + "\t" + dictionary.get(key) + "\n");
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}else if(orderNumber == 2){
Comparator<Integer> comp = new Comparator<Integer>() ;
TreeMap<Integer, String> wordsMap = new TreeMap<Integer, String>(comp);
for(Map.Entry<String, Integer> entry:dictionary.entrySet()){
wordsMap.put(entry.getValue(),entry.getKey());
}
try {
FileWriter writer = new FileWriter(fileName+".txt");
for(Map.Entry<Integer, String> entry: wordsMap.entrySet()){
writer.write(entry.getValue() + "\t" + entry.getKey() + "\n");
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void askForOptions(){
System.out.println("How do you want the result? \nPress 1 to get result in alphabethic order, \nPress 2 to in frequency order.");
int option = myScanner.nextInt();
if (option == 1){
orderNumber = 1;
System.out.println("Thank you! Good luck...");
}else if(option == 2){
orderNumber = 2;
System.out.println("Thank you! Good luck...");
}else{
System.out.println("Invalid choice! Plese try again...");
askForOptions();
}
}
#Override
public int compare(Integer arg0, Integer arg1) {
if (arg0 == arg1) return 0;
if (arg0 > arg1) return 1;
if (arg0 < arg1) return -1;
return 0;
}
}
ÿş are UTF-16 BOM bytes FF FE printed using Windows 1254 codepage, which is your system default I believe.
To read file correcly, you need to skip BOM, which can be done using Apache Commons IO BOMInputStream wrapper:
try (BOMInputStream bis = new BOMInputStream(new FileInputStream(filename));
Scanner in = new Scanner(bis, bis.getBOMCharsetName() == null
? Charset.defaultCharset().name()
: bis.getBOMCharsetName())) {
// read lines
} catch (IOException e) {
// ...
}
Or you can skip those 2 bytes manually as described in answers for this post.

Word frequency count in 2 files

I have wrote Java code to count sum of occurrences. It uses 2 .txt files as input and gives words and frequencies as output.
I would also like to print, which file how many times contains a given word. Do you have any idea how to do this?
public class JavaApplication2
{
public static void main(String[] args) throws IOException
{
Path filePath1 = Paths.get("test.txt");
Path filePath2 = Paths.get("test2.txt");
Scanner readerL = new Scanner(filePath1);
Scanner readerR = new Scanner(filePath2);
String line1 = readerL.nextLine();
String line2 = readerR.nextLine();
String text = new String();
text=text.concat(line1).concat(line2);
String[] keys = text.split("[!.?:;\\s]");
String[] uniqueKeys;
int count = 0;
System.out.println(text);
uniqueKeys = getUniqueKeys(keys);
for(String key: uniqueKeys)
{
if(null == key)
{
break;
}
for(String s : keys)
{
if(key.equals(s))
{
count++;
}
}
System.out.println("["+key+"] frequency : "+count);
count=0;
}
}
private static String[] getUniqueKeys(String[] keys)
{
String[] uniqueKeys = new String[keys.length];
uniqueKeys[0] = keys[0];
int uniqueKeyIndex = 1;
boolean keyAlreadyExists = false;
for(int i=1; i<keys.length ; i++)
{
for(int j=0; j<=uniqueKeyIndex; j++)
{
if(keys[i].equals(uniqueKeys[j]))
{
keyAlreadyExists = true;
}
}
if(!keyAlreadyExists)
{
uniqueKeys[uniqueKeyIndex] = keys[i];
uniqueKeyIndex++;
}
keyAlreadyExists = false;
}
return uniqueKeys;
}
Firstly, instead of using an array for unique keys, use a HashMap<String, Integer>. It's a lot more efficient.
Your best option is to run your processing over each line/file separately, and store these counts separately. Then merge the two counts to get the overall frequencies.
More Detail:
String[] keys = text.split("[!.?:;\\s]");
HashMap<String,Integer> uniqueKeys = new HashMap<>();
for(String key : keys){
if(uniqueKeys.containsKey(key)){
// if your keys is already in map, increment count of it
uniqueKeys.put(key, uniqueKeys.get(map) + 1);
}else{
// if it isn't in it, add it
uniqueKeys.put(key, 1);
}
}
// You now have the count of all unique keys in a given text
// To print them to console
for(Entry<String, Integer> keyCount : uniqueKeys.getEntrySet()){
System.out.println(keyCount.getKey() + ": " + keyCount.getValue());
}
// To merge, if you're using Java 8
for(Entry<String, Integer> keyEntry : uniqueKeys1.getEntrySet()){
uniqueKeys2.merge(keyEntry.getKey(), keyEntry.getValue(), Integer::add);
}
// To merge, otherwise
for(Entry<String, Integer> keyEntry : uniqueKeys1.getEntrySet()){
if(uniqueKeys2.containsKey()){
uniqueKeys2.put(keyEntry.getKey(),
uniqueKeys2.get(keyEntry.getKey()) + keyEntry.getValue());
}else{
uniqueKeys2.put(keyEntry.getKey(), keyEntry.getValue());
}
}
UPDATE : code for word(s) occurences (thanks #George)
This example is for a file, you can use it for multiple files :
public class MyTest {
Map<String,Integer> mapTable;
public MyTest(List<String> wordList){
//initialize map
makeMap(wordList);
}
public void makeMap(List<String> wordList){
mapTable = new HashMap();
for(int i = 0; i < wordList.size(); i++){
//fill the map up
mapTable.put(wordList.get(i), 0);
}
}
//update occurences in a map
public void updateMap(String [] _words){
for(int i = 0; i < _words.length; i++){
updateWordCount(_words[i]);
}
}
public void updateWordCount(String _word){
int value = 0;
//check if a word present
if(mapTable.containsKey(_word)){
value = mapTable.get(_word);
value++;
mapTable.put(_word, value);
}
}
public void DisplayCounts(){
for( String key : mapTable.keySet()){
System.out.println("Word : "+key+"\t Occurrence(s) :"+mapTable.get(key));
}
}
public void getWordCount(){
String filePath = "C:\\Users\\Jyo\\Desktop\\help.txt";
String line = "";
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(filePath);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
String _words[] = null;
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
_words = line.split(" ");
updateMap(_words);
}
// Always close files.
bufferedReader.close();
} catch (Exception e) {
System.out.println("Error :"+e.getMessage());
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
List<String> wordList = new ArrayList<>();
wordList.add("data");
wordList.add("select");
MyTest mt = new MyTest(wordList);
mt.getWordCount();
mt.DisplayCounts();
}
}
import java.io.;
import java.util.;
public class file1{
public static void main(String[] args) throws Exception{
HashMap<String,Integer> words_fre = new HashMap<String,Integer>();
HashSet<String> words = new HashSet<String>();
try{
File folder = new File("/home/jsrathore/Dropbox/Semester 6th/IR_Lab/lab_01/one");
File[] listOfFiles = folder.listFiles();
BufferedReader bufferedReader=null;
FileInputStream inputfilename=null;
BufferedWriter out= new BufferedWriter(new OutputStreamWriter(new FileOutputStream("outfilename.txt",false), "UTF-8"));
for(File file : listOfFiles){
inputfilename= new FileInputStream(file);
/*System.out.println(file); */
bufferedReader= new BufferedReader(new InputStreamReader(inputfilename, "UTF-8"));
String s;
while((s = bufferedReader.readLine()) != null){
/*System.out.println(line);*/
s = s.replaceAll("\\<.*?>"," ");
if(s.contains("॥") || s.contains(":")|| s.contains("।")||
s.contains(",")|| s.contains("!")|| s.contains("?")){
s=s.replace("॥"," ");
s=s.replace(":"," ");
s=s.replace("।"," ");
s=s.replace(","," ");
s=s.replace("!"," ");
s=s.replace("?"," ");
}
StringTokenizer st = new StringTokenizer(s," ");
while (st.hasMoreTokens()) {
/*out.write(st.nextToken()+"\n");*/
String str=(st.nextToken()).toString();
words.add(str);
}
for(String str : words){
if(words_fre.containsKey(str)){
int a = words_fre.get(str);
words_fre.put(str,a+1);
}else{
words_fre.put(str,1);/*uwords++;//unique words count */
}
}
words.clear();
/*out.write("\n");
out.close();*/
}
Object[] key = words_fre.keySet().toArray();
Arrays.sort(key);
for (int i = 0; i < key.length; i++) {
//System.out.println(key[i]+"= "+words_fre.get(key[i]));
out.write(key[i]+" : "+words_fre.get(key[i]) +"\n");
}
}
out.close();
bufferedReader.close();
}catch(FileNotFoundException ex){
System.out.println("Error in reading line");
}catch(IOException ex){
/*System.out.println("Error in reading line"+fileReader );*/
ex.printStackTrace();
}
}
}
Late answer, however below code will count word frequency efficiently if there are multiple files
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;
public class WordCounter implements Runnable {
private final Scanner scanner;
private Map<String, AtomicLong> sharedCounter;
public WordCounter(Scanner scanner, Map<String, AtomicLong> sharedCounter) {
this.scanner = scanner;
this.sharedCounter = sharedCounter;
}
public void run() {
if (scanner == null) {
return;
}
while (scanner.hasNext()) {
String word = scanner.next().toLowerCase();
sharedCounter.putIfAbsent(word, new AtomicLong(0));
sharedCounter.get(word).incrementAndGet();
}
}
public static void main(String[] args) throws IOException {
// Number of parallel thread to run
int THREAD_COUNT = 10;
List<Path> paths = new ArrayList<>();
// Add path
paths.add(Paths.get("test1.txt"));
paths.add(Paths.get("test2.txt"));
// Shared word counter
Map<String, AtomicLong> sharedCounter = new ConcurrentHashMap<>();
ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT);
for (Path path : paths) {
executor.execute(new WordCounter(new Scanner(path), sharedCounter));
}
executor.shutdown();
// Wait until all threads are finish
while (!executor.isTerminated()) {
}
System.out.println(sharedCounter);
}
}

Java - store elements of ArrayList into separate blocks

so here is ALL of my code, which, in summary, standardises two text files then prints out the result.
import java.io.*;
import java.util.*;
public class Plagiarism {
public static void main(String[] args) {
Plagiarism myPlag = new Plagiarism();
if (args.length == 0) {
System.out.println("Error: No files input");
}
else if (args.length > 0) {
try {
for (int i = 0; i < args.length; i++) {
BufferedReader reader = new BufferedReader (new FileReader (args[i]));
List<String> foo = simplify(reader);
for (int j = 0; j < foo.size(); j++) {
System.out.print(foo.get(j));
}
}
}
catch (Exception e) {
System.err.println ("Error reading from file");
}
}
}
public static List<String> simplify(BufferedReader input) throws IOException {
String line = null;
List<String> myList = new ArrayList<String>();
while ((line = input.readLine()) != null) {
myList.add(line.replaceAll("[^a-zA-Z0-9]","").toLowerCase().trim());
}
return myList;
}
}
The next bit I want to implement is this: Using the command line, the 3rd argument will be any integer(size of blocks) which the user enters. I have to use this then to store the elements of that array into separate blocks which overlap. EG: The cat sat on the mat, block size 4. Block 1 would be: Thec Block 2: heca Block 3: ecat, and so on, until it reaches the end of the array.
Any ideas?
Thanks in advance guys.
To get the block size use this :
if(args.length != 4)
return;
int blockSize = Integer.valueOf(args[3]);
This an example that could help you
import java.util.*;
public class Test {
public static void main(String[] args) {
String line = "The dog is in the house";
line = line.replace(" ", "");
List<String> list = new ArrayList<String>();
for (int i = 0; i <= line.length() - 4; i++)
list.add(line.substring(i, i + 4));
System.out.println(list);
}
output :
[Thed, hedo, edog, dogi, ogis, gisi, isin, sint, inth, nthe, theh, heho, ehou, hous, ouse]
Is that what you want to do
WE can code it in mulitple ways, here is one example.
Input 3 arguments first 2 are files and 3rd one is the block size:
File1 contain: this is a boy
File2 contain: this is a girl
block size: 4
Expected Output:
this hisi isis sisa isab sabo aboy boyt oyth ythi this hisi isis sisa isag sagi agir girl
Program:
import java.io.;
import java.util.;
public class Plagiarism {
public static void main(String[] args) {
//Plagiarism myPlag = new Plagiarism();
/*args = new String[3];
Scanner s = new Scanner(System.in);
System.out.println("Enter the 1st file path");
args[0] = s.next();
System.out.println("Enter the 2nd file path");
args[1] = s.next();
System.out.println("Enter size of block");
args[2] = s.next();*/
int blockSize = Integer.valueOf(args[2]);
StringBuilder wholeContent = new StringBuilder("");
if (args.length == 0) {
System.out.println("Error: No files input");
}
else if (args.length > 0) {
try {
for (int i = 0; i < args.length-1; i++) {
BufferedReader reader = new BufferedReader (new FileReader (args[i]));
List<String> foo = simplify(reader);
for (int j = 0; j < foo.size(); j++) {
//System.out.print(foo.get(j));
wholeContent.append(foo.get(j));
}
}
System.out.println("The content of Line is = "+ wholeContent);
System.out.println("The content of line based on the block size = "+ blockSize + " is:");
for(int j=0; j<=(wholeContent.length()-blockSize); j++){
System.out.print(wholeContent.substring(j, j+4));
System.out.print(" ");
}
}
catch (Exception e) {
e.printStackTrace();
System.err.println ("Error reading from file");
}
}
}
public static List<String> simplify(BufferedReader input) throws IOException {
String line = null;
List<String> myList = new ArrayList<String>();
while ((line = input.readLine()) != null) {
if(!" ".equals(line))
myList.add(line.replaceAll("[^a-zA-Z0-9]","").toLowerCase().trim());
}
return myList;
}
}
All you are asking to do can be done with string manipulation. First use replaceAll() to remove your spaces, then use a for loop and substring() to create your blocks.
for your for loop you need to modify it so that it reads the two texts, then uses the 3rd argument as the block size so you would change your for loop from:
for(int i = 0; i<args.length;i++)
to:
for(int i = 1; i<3; i++)
this reads the first two arguments but not the third

How do you store each value separately using comma then they store into separate array?

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.

Categories