How do I utilize an array of a specific class? - arrays

I am trying to input a file that contains the first and last names of several individuals from a file into a java program. I have a People class that has two Strings for the first and last names, as well as, accessors and mutators to access the information. Inside my main method, I have a while loop that brings in each person line by line until the end of the file. It is suppose to create a new instance of Person through the constructor for each line and make a copy to the array. When I print out the contents of the array once the while loop is over with, it seems that the array is filled with the information of the last person in the file. However, if I comment out the String[] values = line.split("\t"); and Person child = new Person(values[0], values[1]); lines and use a double dimensional array to hold a copy of all the information in the file, then it works fine. Is there something that I am doing wrong that is preventing me from retaining a copy of all the individual’s names contained in the file in the People array?
public class Person
{
protected static String first;
protected static String last;
private static int id;
public Person(String l, String f)
{
last = l;
first = f;
} // end of constructor
public String getFirst()
{
return first;
} // end of getFirst method
public static String getLast()
{
return last;
} // end of getLast method
public static int getID()
{
return id;
} // end of getLast method
public static void setFirst(String name)
{
first = name;
} // end of setFirst method
public static void setLast(String name)
{
last = name;
} // end of setLast method
public static void setID(int num)
{
id = num;
} // end of setLast method
} // end of Person class
public class Driver
{
public static void main(String arg[])
{
Person[] temp = new Person[10];
try
{
BufferedReader br = new BufferedReader(new FileReader(arg[1]));
String line = null;
int counter = 0;
while ((line = br.readLine()) != null)
{
String[] values = line.split("\t");
Person child = new Person(values[0], values[1]);
temp[counter] = child;
System.out.println("Index " + counter + ": Last: " + child.getLast() + " First: " + child.getFirst());
System.out.println("Index " + counter + ": Last: " + temp[counter].getLast() + " First: " + temp[counter].getFirst() + "\n");
counter++;
}
br.close();
}
catch(Exception e)
{
System.out.println("Could not find file");
}
for(int row = 0; row < 7; row++)
{
System.out.print("Row: " + row + " Last: " + temp[row].getLast() + " First: " + temp[row].getFirst() + "\n");
}
}
} // end of Driver class

The fields in class Person should not be static, a static field means shares the value for all instances of the class, that means all the 10 instances Person have the same "first", "last" and "id" values. And you need to change the methods of Person to non-static too, since static method cannot access static fields.

Related

How to fix method printing null for some iterations?

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

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

Missing rows from list when using dynamic task in dotnet

I am new in using TPL in .Net applications. While creating a simple console application to achieve some parallel tasks those are dynamically created, I am stuck with some issues.
Problem here is that when 10 tasks are created and run, although the console is showing all the 10 tasks, when writing those into a log file after putting a delay between consoling and logging, the log file misses some of the items randomly.
Below is my sample code (This is just a skeleton of my actual code)
class Program
{
public static int datacount = 10;
static void Main(string[] args)
{
List<Task> tasks = new List<Task>();
var s1 = DateTime.Now;
var transList = GenerateTransactionList();
foreach (var transaction in transList)
{
Transactions transactionNew = new Transactions();
transactionNew = transaction;
tasks.Add(Task.Factory.StartNew(() => serialMethod(transactionNew)));
}
Task.WhenAll(tasks).Wait();
Console.WriteLine("Completed!!!");
}
private static List<Transactions> GenerateTransactionList()
{
Random r = new Random();
List<Transactions> transactionList = new List<Transactions>();
for (int i = 1; i <= datacount; ++i)
{
Transactions tr = new Transactions();
tr.ID = 0;
tr.Amount = r.Next(1, 10);
tr.Created_By = "Iteration" + i;
tr.Notes = "Iteration" + i;
tr.Created_On = DateTime.Now;
transactionList.Add(tr);
}
return transactionList;
}
private static async Task<string> serialMethod(Transactions tlist)
{
Console.WriteLine("Started Serial Iteration" + tlist.Notes);
try
{
Console.WriteLine("Finished Serial Iteration" + tlist.Notes);
Thread.Sleep(10000);//doing some time consuming process
WriteLog("Parallel2", DateTime.Now, DateTime.Now, tlist.Notes);
return "Success";
}
catch (Exception ex)
{
Console.WriteLine("serialmethod" + ex.Message);
return "Failure";
}
}
public static void WriteLog(string type,
DateTime startTime, DateTime endTime,
string dataSet)
{
try
{
string logFolderPath = AppDomain.CurrentDomain.BaseDirectory + #"\Logs";
if (!Directory.Exists(logFolderPath))
Directory.CreateDirectory(logFolderPath);
string logFilePath = logFolderPath + #"\Log_" + DateTime.Today.ToString("yyyy.MM.dd") + ".csv";
string line = string.Empty;
if (!File.Exists(logFilePath))
{
line = #"""Type"",""Start Time"",""End Time"",""Duration"",""Iteration""";
writeLineToFile(logFilePath, line);
}
string duration = (endTime - startTime).ToString();
line = "\"" + type + "\"," +
"\"" + startTime.ToString("MM/dd/yyyy hh:mm:ss tt") + "\"," +
"\"" + endTime.ToString("MM/dd/yyyy hh:mm:ss tt") + "\"," +
"\"" + duration + "\"," +
"\"" + dataSet + "\"";
writeLineToFile(logFilePath, line);
}
catch (Exception)
{
//do nothing
}
}
private static void writeLineToFile(string fileName, string line)
{
using (var writer = new StreamWriter(fileName, true))
{
writer.WriteLine(line);
}
}
}
class Transactions
{
public int ID { get; set; }
public decimal Amount { get; set; }
public int Points { get; set; }
public string Notes { get; set; }
public string Created_By { get; set; }
public DateTime Created_On { get; set; }
}
Do you have any idea why this is happening. I have tried using ConcurrentBag instead of list. But that too is not helping. Please guide and let me know if I am missing anything or my implementation is completely wrong.
There a re a bunch of error-prone lines in your code:
You're overriding the reference for transaction in your foreach loop
You're using StartNew method instead of Tas.Run
You're using blocking WaitAll instead of await WhenAll, so you do block one thread in your application for no reason
You can simply switch to Parallel.Foreach instead of foreach
And most important: you're writing to the same file from different threads simultaneously, so they are basically interrupting each other. Either use some blocking to write the file (which cannot be done in parallel) or use some library for logging, like NLog or whatever, so it will handle logging for you
Your threads can run into situation when some of them trying to create file when other already done that, so move out the creation logic for file into one place (which the libraries like NLog will do for you properly)
Try to use object initializers instead of setting one property after another:
var tr = new Transactions
{
ID = 0,
Amount = r.Next(1, 10),
Created_By = "Iteration" + i,
Notes = "Iteration" + i,
Created_On = DateTime.Now
}

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.

"Undefined for type" and "cannot make static reference"?

I'm writing a program but I'm unable to call a few of the methods I made. The errors are as follows:
-method reportMenu(String) in the type CommissionReportSystem is not applicable for the arguments ()
-Cannot make a static reference to the non-static method getSalesData() from the type CommissionReportSystem
-The method computeTotalSales() is undefined for the type CommissionReportSystem
-The method computeSalesCommission(double) in the type CommissionReportSystem is not applicable for the arguments ()
-The method showAgentCommission(double) in the type CommissionReportSystem is not applicable for the arguments ()
I've tried a lot of fixes but nothing seems to be sticking and I'm unsure of how to proceed. I've included the relevant parts of the code below. I would appreciate any tips on how to fix any of these. Thank you!
import java.io.*;
import java.text.*;
import java.util.*;
public class CommissionReportSystem {
private static final String String = null;
public static void main(String[] args) {
getSalesData ();
computeTotalSales ();
computeSalesCommission ();
showAgentCommission ();
shutdown ();
}
String [] getSalesData (){
String [] data = new String [2];
String ticketsSold = "";
String ticketPrice = "";
String buffer = new String ();
data[0] = buffer;
data[1] = buffer;
BufferedReader br = null;
try {
br = new BufferedReader (new InputStreamReader(System.in));
System.out.print ("Enter tickets sold:");
buffer = br.readLine ();
ticketsSold = buffer;
System.out.print ("Enter ticket price:");
buffer = br.readLine ();
ticketPrice = buffer;
} catch (Exception e) {
System.out.println ("Invalid entry");
}
data [0] = ticketsSold;
data [1] = ticketPrice;
return data;
}
public static double totalSales (String ticketsSold, String ticketPrice){
int ticketsSoldNum = Integer.parseInt(ticketsSold);
double ticketPriceNum = Double.parseDouble(ticketPrice);
double totalSalesNum = ticketsSoldNum * ticketPriceNum;
return totalSalesNum;}
public static final double computeSalesCommission (double totalSalesNum){
final double rate1 = 0.025;
final double rate2 = 0.0375;
final double rate3 = 0.0425;
final double salesLimit1 = 2000;
final double salesLimit2 = 4000;
final double agentCommission= 0;
if (totalSalesNum <= 2000) {
agentCommission = rate1 * totalSalesNum;
}
else if (totalSalesNum <= 4000){
agentCommission = rate2 * totalSalesNum;
}
else (totalSalesNum > 4000){
agentCommission = rate3 * totalSalesNum;
}
return agentCommission;
}
public static void showAgentCommission (double agentCommission){
System.out.format ("Congratulation agent Cindy Smith, your current daily commission:" + agentCommission);
}
public static void shutdown (){
System.out.format ("Thank you for your time! Have a great day!");
}
public static void handleInvalidData (){
}
}
1) getSalesData() is an instance method. If you want to call an instance method, create an object of the class and call method using that. Else you have to make the method static. Remember one the thing you cannot access the instance variables inside static method.
2) There is no method computeTotalSales() in your class.
3) computeSalesCommission() requires an argument of type double. You have called it without any argument.
4) The last comment is also valid for showAgentCommission().

Resources