How to fix method printing null for some iterations? - file

Write a program that shall calculate the vocabulary richness of a text in a file and the frequency of the most common word. The vocabulary richness is the number of words in the text divided by the number of distinct words. The frequency of a word is the number of times the word is mentioned in the text divided by the total number of words in the text.
Define and implement class WordCounter with two private fields String word and int count, constructor WordCounter(String word), and public methods String getName(), int getCount(), and void addToCounter().
Define and implement class Corpus (as in text corpus) with one private field ArrayList<WordCounter> words, constructor Corpus(BufferedReader infile), and public methods double getVocabularyRichness() and String getMostFrequentWord().
Implement a test program (as the public static void main method in Corpus) that reads all files in a specific folder, creates a Corpus object from each (previously opened) file, and saves the requested statistics into another file stats.csv. You can either create a new Corpus object for each file or define an ArrayList<Corpus> of the corpora.
Each line of the CSV file must consist of three fields separated by commas (but no spaces!): the file name, the vocabulary richness, and the most frequently used word. Run your program on all Shakespeare's plays. Submit the CSV file together with the Java file.
I wrote what I think is the correct implementation of the HW problem because it works properly for some of the text files, however only the words.get(i).getName() (I tested with words.get(i).getCount()) method will print a blank space for some of the files. I have tried everything, and can't seem to figure it out. Can you please give me a hint or some guidance as to how to fix this issue?
public class Corpus {
private ArrayList<WordCounter> words = new ArrayList <WordCounter>() ;
Corpus(BufferedReader infile){
String ln;
try {
while((ln = infile.readLine()) != null) {
for (String word : ln.toLowerCase().split("([,.\\s]+)")) {
int reference = 0;
for(int i = 0; i < words.size(); i++) {
if (word.equals(words.get(i).getName())) {
reference++;
words.get(i).addToCounter();
} }
if (reference==0) { words.add(new WordCounter(word)); }
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public double getVocabularyRichness() {
int word_count=0;
for(int i = 0; i < words.size(); i++) {
word_count=word_count+words.get(i).getCount();
}
return (double)word_count/(double)words.size();
}
public String getMostFrequentWord() {
String winner = "*AN ERROR OCCURRED*";
int max_count = 0;
for(int i = 0; i < words.size(); i++) {
if(words.get(i).getCount() > max_count){
max_count = words.get(i).getCount();
}
}
for(int i = 0; i < words.size(); i++) {
if(words.get(i).getCount() == max_count){
winner = words.get(i).getName();
}
}
//winner="Test " + String.valueOf(words.get(i).getName());;
//return String.valueOf(max_count);
return winner;
}
public static void main(String [] args) throws Exception{
BufferedWriter writer = null;
File folder_location = new File("/Users/joaquindelaguardia/Desktop/Shakespeare");
File[] file_array = folder_location.listFiles();
for(File iteration_file: file_array) {
FileReader current_file = new FileReader(iteration_file);
BufferedReader infile = new BufferedReader(current_file);
Corpus obj1 = new Corpus(infile);
String file_name = iteration_file.getName();
String frequent_word = obj1.getMostFrequentWord();
String vocabulary_richness = String.valueOf(obj1.getVocabularyRichness());
System.out.println(file_name);
System.out.println(frequent_word);
System.out.println(vocabulary_richness);
System.out.println("-----------------------------");
//FileWriter file_writer = new FileWriter("/Users/joaquindelaguardia/Desktop/stats.csv");
//writer = new BufferedWriter(file_writer);
//String output = file_name+", "+frequent_word+", "+vocabulary_richness + "\n";
//writer.append(output);
}
//writer.close();
}
}
public class WordCounter {
private String word;
private int count=1;
WordCounter(String word){
this.word=word;
}
public String getName() {
return word;
}
public int getCount() {
return count;
}
public void addToCounter() {
count++;
}
}
Im testing the information by printing before appending to file, and as you can see with the small fragment of the output included below, for some cases it prints the most common word (and) while in the second case it doesn't print anything.
shakespeare-lovers-62.txt
and
2.2409948542024014
shakespeare-julius-26.txt
6.413205537806177

Related

Copying all Lines from One file to other file in a Fair Random Manner in Big O(n) running time complexity

you have a file with multiple string lines and u have to put it into another file in fair random manner, how would you implement it with linkedlist and array only given as constraint.
the distribution should be random i.e. should not follow any pattern which is guessable i.e. round-robbin or something like that.
public class FairRandomDistributionDataFromOneToOtherFile {
public static void main(String[] args) {
// Driver Program to read the lines into the String Array.
FileReader fr = null;
LineNumberReader lnr = null;
try {
// Please Pass the File Path to the below filereader to run this program
fr = new FileReader("/home/sgarg/Documents/workspace-spring-tool-suite-4-4.10.0.RELEASE/Interveiw/src/com/sunil/stringfile");
lnr = new LineNumberReader(fr);
lnr.mark(500); // some random read ahead limit, I just choose 5000 randomly
lnr.skip(Integer.MAX_VALUE);
int totalLines = lnr.getLineNumber();
String[] data = new String[totalLines];
// resetting to mark, basically start of the file
lnr.reset();
for (int i=0; i<totalLines; i++) {
data[i] = lnr.readLine();
}
shuffleAndWriteDataToNewFile(data);
System.out.println(Arrays.toString(data));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* #param data - All lines of the files read and passed as String into this String[]
*
*/
public static String[] shuffleAndWriteDataToNewFile(String[] data) {
int len = data.length;
int rand= 0;
for (int i=0; i < len; i++) {
// choose the next random number between the all current valid lines
rand = getNextRandomNumber(len - i);
// Now whatever the random line we get, we will move it to the end of the array and assume that
// next random number generator will generate random lines from 0 to len - i
swapLine(data, i, rand);
// this way our random lines getting settled in the last index of the array which keeps decrementing with loop iteration
// this way we dont need to take a 2nd array to store the lines and complexity vise it is an O(N) solution as we are iterating
// over the array once.
}
return data;
}
/**
* Swap two String Objects in the given String Array.
*/
public static void swapLine(String[] data, int curr, int rand) {
int len = data.length;
String temp = data[len-1 - curr];
data[len -1 -curr] = data[rand];
data[rand] = temp;
}
public static int getNextRandomNumber(int numOfElements) {
return (int)(Math.random() * numOfElements);
}
}

How can I create a loop to randomly assign values to each characteristic of an array of class instances

So I am creating a card game that requires different cards, so I created a card class in which I declared the string value names and other integer values that are the powers eg. Intelligence
public static class hero{
static String name;
static int strength;
static int intellect;
static int flight;
static int tech;
}
So I created an array of instances of these classes.
Their names are read from a text file and assigned to the name value.
Q1) I am having trouble with reading through the file and assigning the string to the name value of each instance of the class.
This is what I've done so far
public static void readLines(File f)throws IOException{
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String line;
while((line = br.readLine()) != null){
System.out.println(line);
}
br.close();
fr.close();
}
static File f = new File("C:/Users/jeff/Desktop/test/names.txt");
try{
readLines(f);
} catch (IOException e){
e.printStackTrace();
}
Q2)The part I am also having trouble with is the part where I need to create a loop to randomly assign values to each power of each instance of a class.
Here's what I've done so far
{
hero [] cards = new hero[cardNumber];
for(int i=4;i<cardNumber;i++){ cards[i]=new hero();}
Random rand = new Random();
for(int i=0; i<cards.length; ++i)
{
cards[i].strength = rand.nextInt(25) + 1;
cards[i].intellect = rand.nextInt(25) + 1;
cards[i].flight = rand.nextInt(25) + 1;
cards[i].tech = rand.nextInt(25) + 1;
}
But when I print out the values all the instances have the same value for their powers.
Eg Card 12 Intelligence = 6
And Card 14 Intelligence = 6
Can anyone please help me with these issues, and any guidance will be highly appreciated
Thank you

How to call an array from a static method?

In this code, how do I call an array globally for other methods to use?
Background info on my code, we are asked to scan a file that contains DNA strands then translating it to an RNA Strand.
I receive the error: " cannot find symbol - variable dna " when i call the dna array on the translation method (it can't find dna.length) for(int i=0; i < dna.length; i++){
public class FileScannerExample
{
public static void main(String[] args) throws IOException
{
//This is how to create a scanner to read a file
Scanner inFile = new Scanner(new File("dnaFile.txt"));
String dnaSequence = inFile.next();
int dnalength = dnaSequence.length();
String[] dna = new String[dnalength];
for(int i=0; i<=dna.length-2 ; i++)
{
dna[i]=dnaSequence.substring(i,i+1); //looking ahead and taking each character and placing it in the array
}
dna[dna.length-1]=dnaSequence.substring(dna.length-1); //reading the last spot in order to put it in the array
//Testing that the array is identical to the string
System.out.println(dnaSequence);
for(int i = 0 ; i<=dna.length-1; i++)
{
System.out.print(dna[i]);
}
}
public void translation()
{
for(int i=0; i < dna.length; i++){
//store temporary
if (dna[i] = "A"){
dna[i] = "U";
}
if(dna[i] = "T"){
dna[i] = "A";
}
if(dna[i] = "G"){
dna[i]= "C";
}
if(dna[i] = "C"){
dna[i] = "G";
}
}
}
}
you need to bring the symbol into scope before you can reference it. you can do this, either by pulling it up into a higher scope (as a field in the class), or by sending it into the local scope by passing it as a method parameter.
As a class member:
public class Test
{
private String myField;
void A() {
myField = "I can see you";
}
void B() {
myField = "I can see you too";
}
}
As a method parameter:
public class Test
{
void A() {
String myVar = "I can see you";
System.out.println(myVar);
B(myVar);
}
void B(String param) {
param += " too";
System.out.println(param);
}
}
Note that in order to see an instance member, you must be referencing it from a non-static context. You can get around this by declaring the field as static too, although you want to be careful with static state in a class, it generally makes the code more messy and harder to work with.

Implementing arrays for a Palindrome program

I am working on creating a program that reads strings in from a data file calles "palindromes.txt" and which stores the strings in a one-dimensional array. The program is supposed to inspect each of the strings and detrmine whether or not each one is a pallindrome. It's supposed to show output on the screen and into a file called "output.txt".
The problem i'm having is that I can't figure out how to get the input/output correct and i'm not sure the best way to utilize the arrays.
Very new to this, please advise if you can. :)
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Palindromes2
{
public static boolean isPalindrome(String dirtystr)
{
dirtystr = dirtystr.toLowerCase().replaceAll("[^a-zA-Z]+","");
int length = dirtystr.length(), middle = length / 2;
for (int x = 0; x < middle; x++)
if (dirtystr.charAt(x) != dirtystr.charAt(length - x - 1))
return false;
return true;
}
public static void main(String[] args) throws IOException
{
File inputFile = new File("output.txt");
try (Scanner scanner = new Scanner(inputFile))
{
while (scanner.hasNextLine())
{
String dirtystr = scanner.nextLine();
if (isPalindrome(dirtystr))
{
System.out.println(dirtystr + " IS a palindrome.");
}
else
{
System.out.println(dirtystr + " is NOT a palindrome.");
}
}
}
}
}

how can i store a text file into an array?

so that later i can parse the array and if the line contains 3 doubles store it into an array of object type? ill later have to store the lines with 3 doubles into another array.
here's an example of my code so far
public static void readFile(){
Scanner scnr = null;
File info = new File("info.txt");
try {
scnr = new Scanner(info);
} catch (FileNotFoundException e) {
System.out.println("file not found");
e.printStackTrace();
}
int counterLines = 0;
String nextLine = "";
while(scnr.hasNextLine()){
nextLine = scnr.nextLine();
counterLines ++;
}
System.out.println(counterLines);
String[] infoArray = new String[counterLines];
for(int i = 0; i < counterLines; i++){
infoArray[i] = scnr.nextLine();
System.out.println(infoArray[i]);
You can probably spilt the text of the file into individual words using String.split() which gives you a String array.

Resources