Sorry this is probably a dumb question. I'm kinda new to coding and I'm using Processing, which is based off Java.
I have an array of 5 rectangle objects in my main program
for (int i = 0; i < portals.length; i++)
{
portals[i] = new Portals();
}
when displayed, I call this method from my Portals class
void display()
{
rectMode(CENTER);
rect(xLoc, yLoc, rad, 30);
}
the xLoc and yLoc are determined randomly. How would you go about assigning a number (like an identity) to each object in the array so that I can refer to that specific rectangles's location and where would I put it in my code?
You can have a filed in the class that makes it identifiable. Like:
public class Portals {
int xLoc;
int yLoc;
String name;
...
public Portals(String name){
this.name = name;
}
public String getName(){
return name;
}
}
Then you can try to access by name in array
for (int i = 0; i < portals.length; i++)
{
portals[i] = new Portals("Name");
}
for (Portals p : portals){
if ("Name".equals(p.getname()) {
// do somthing
}
}
Or you can use a Map. But that may be more advanced than your knowledge, so I won't give code. But that's another suggestion.
Edit: with Map
Map<String, Portals> map = new HashMap<String, Portals>();
Key Value
map.put("nameForPortal", new Portals());
map.put("anotherNameForPortal", new Portals());
// To access the portal, you can get by the key
Portals p = map.get("nameForPortal");
Related
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
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
This code has been working fine for years.
public PageReference chkinst() {
i=0;
integer j=0;
Set<String> aSearchSet = new Set<String>();
List<Lead> lList = ui;
for (Lead l : lList) {
aSearchSet.add(l.company);
}
Account[] accountToCreate = new Account[]{};
Map<String,Account> companyToAccountMap = new Map<String,Account> ();
for (Account a: [select id, Name from Account where name IN :aSearchSet])
companyToAccountMap.put(a.name,a);
for (Lead l : lList) {
if (!companyToAccountMap.containsKey(l.company)){
Account act = new Account(Name = l.Company , Country__c = l.Country__c );
accountToCreate.add(act);
j = j +1;
}
}
insert accountToCreate;
if(j == 0) {
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'All leads have correct institution names'));
} else{
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,j + ' Institutions created'));
}
return null;
}
Today, it gave me the following error:
Maximum view state size limit (135KB) exceeded. Actual view state size for this page was 135.078KB
Does anyone know why?
Thanks,
It's hard to tell from this code snippet. But if I had to guess. It looks like your companyToAccountMap is a class level variable, and it's probably returning more records now then it used to. If you don't need that map anywhere else in the controller, I would move it to a method level or make it transient.
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.
What I need to achieve is to import data from a text file that contains two columns of doubles as follows:
201.0176 1.06E+03
201.7557 1.11E+01
202.0201 2.02E+02
202.2064 9.76E+00
202.8342 1.11E+01
203.0161 2.02E+02
203.1638 9.61E+00
203.3843 1.13E+01
There are up to about 50,000 lines of these data. I want each column to be imported into a separate array but I cannot work out how to identify between the separate columns. I have tried the following:
public class CodeTests {
public static ArrayList assignArray(String filePath) throws FileNotFoundException {
Scanner s = new Scanner(new File(filePath));
ArrayList<Double> list = new ArrayList<Double>();
while (s.hasNext()){
list.add(s.nextDouble());
}
s.close();
return list;
}
public static void main(String[] args) throws IOException {
/*
*
*/
ArrayList arrayMZ;
arrayMZ = assignArray("F:/Stuff/Work/Work from GSK/From Leeds/ja_CIDFragmenter/testFile.txt");
for(int i = 0; i < arrayMZ.size(); i++)
System.out.println(arrayMZ.get(i));
System.out.println("End");
}
}
From running this I get the output:
run:
201.0176
1060.0
201.7557
11.1
202.0201
202.0
202.2064
9.76
202.8342
11.1
203.0161
202.0
203.1638
9.61
203.3843
11.3
End
BUILD SUCCESSFUL (total time: 1 second)
Can anyone help me either separate these columns into two arrays or even into a single 2D array under the columns of array[0] with the first data column in it and array[1] with the second. i.e. :
[0] [1]
201.0176 1.06E+03
201.7557 1.11E+01
202.0201 2.02E+02
202.2064 9.76E+00
202.8342 1.11E+01
203.0161 2.02E+02
203.1638 9.61E+00
203.3843 1.13E+01
I've tried to make this as clear as I can but if there is anything else please let me know.
Thanks
You could do something like this:
public static ArrayList[] assignArray(String filePath) throws FileNotFoundException {
Scanner s = new Scanner(new File(filePath));
ArrayList[] list = new ArrayList[2];
ArrayList<Double> col1 = new ArrayList<Double>();
ArrayList<Double> col2 = new ArrayList<Double>();
while (s.hasNext()){
String[] data = s.nextLine().split("\\s+");
col1.add(Double.parseDouble(data[0]));
col2.add(Double.parseDouble(data[1]));
}
s.close();
list[0] = col1;
list[1] = col2;
return list;
}
and obtain an array of two ArrayList with your data.
Something like:
for(int i = 0; i < arrayMZ.size() / 2; i+=2)
System.out.printf("%.4f\t%E\n", arrayMZ.get(i), arrayMZ.get(i + 1));