Setters And Getters to different Class - java

My problem is that, simply I don't know what code to use to get my value from my getX method to my other classses main method.
package hangman;
public class Hangman {
private int triesLimit;
private String word;
public void setTriesLimit(int triesLimit) {
this.triesLimit = triesLimit;
}
public void setWord(String word) {
this.word = word;
}
public int getTriesLimit() {
return this.triesLimit;
}
public String getWord() {
return this.word;
}
#Override
public String toString() {
return ("Enter Secret Word " + this.getWord()
+ ".\nEnter max # of tries (Must be under 7) "
+ this.getTriesLimit());
}
}
Thats from the sub-class and I am trying to store the value of the triesLimit into the main of this classes main method
package hangman;
public class PlayHangman {
public static void main(String[] args) {
Hangman hangman = new Hangman();
Scanner scn = new Scanner(System.in);
int triesCount = 0;
int correctCount = 0;
hangman.toString();
int triesLimit = hangman.getTriesLimit();
String secretWord = hangman.getWord();
StringBuilder b = new StringBuilder(secretWord.length());
for (int i = 0; i < secretWord.length(); i++) {
b.append("*");
}
char[] secrectStrCharArr = secretWord.toCharArray();
int charCnt = secretWord.length();
for (int x = 0; triesCount < triesLimit; triesCount++) {
while (charCnt >= 0) {
System.out.println("Secrect Word :" + b.toString());
System.out.println("Guess a letter :");
char guessChar = scn.next().toCharArray()[0];
for (int i = 0; i < secrectStrCharArr.length; i++) {
if (guessChar == secrectStrCharArr[i]) {
b.setCharAt(i, guessChar);
correctCount++;
} else if (guessChar != secrectStrCharArr[i]) {
triesCount++;
System.out.println("Incorrect: " + triesCount);hangmanImage(triesCount,correctCount);
}
}
}
}
}
I tried looking it up on here but couldn't find setters and getters used in a sub/superclass

You need to create an instance of the class in the main method to access the variables and method available in that class like so
public class PlayHangman {
public static void main(String[] args) {
Hangman hangman = new Hangman();
hangman.setTriesLimit(2)
int value = hangman.getTriesLimit();
}
You can look into static keyword to access the value directly but that requires a bit more understanding of OOP's and JAVA.
This should work fine.
Hope it helps :)
EDITED
ToString method is just to convert everything in your model class to String which you have done correctly,but you have implemented incorrectly.... Change your ToString content so
#Override
public String toString() {
return ("The Secret Word you entered: " + this.getWord()
+ ".\n The max # of tries (Must be under 7): "
+ this.getTriesLimit());
}
You have initialized Scanner which does what you want, to ask the user to enter the values but again you haven't implemented it so add this to your main method
Scanner scn = new Scanner(System.in);
hangman.setTriesLimit(scn.nextInt());
hangman.setWord(scn.next());
hangman.toString()//Will work now
Trial and error is your best friend now :)
and Google some of the issues rather than waiting for an answer :)

Like rohit said, this is as simple as understand the basics of OOP, specific the encapsulation.
If you want to get a little deeper into OOP patterns, you could use the Observer pattern. This allows you to change the status of any class instance, even if they're not related by inheritance, aggregation, etc.
You can scale the solution by making List of Observer
Your observable interface
public interface IObservable {
// Set the observer
public void setObserver(IObserver iObserver);
// Notify the observer the current status
public void notifyObserver();
}
Your observer interface
public interface IObserver {
public void update(boolean status);
}
Your observer implementation
public class PlayHangman implements IObserver {
private boolean status = false;
public void printStatus() {
System.out.println("Status: " + (this.status ? "Win" : "Lose"));
}
#Override
public void update(boolean status) {
// The instance status is updated
this.status = status;
// Print the current status
this.printStatus();
}
}
Your observable implementation
public class Hangman implements IObservable{
private String goalWord = "";
private String currentWord = "";
private int triesLimit = 0;
private int tries = 0;
private IObserver iObserver;
public Hangman(String goalWord, int triesLimit) {
this.goalWord = goalWord;
this.triesLimit = triesLimit;
}
public void setCurrentWord(String currentWord) {
this.currentWord = currentWord;
this.notifyObserver();
}
public void addTry() {
this.tries++;
this.notifyObserver();
}
#Override
public void setObserver(IObserver iObserver) {
this.iObserver = iObserver;
}
#Override
public void notifyObserver() {
// True = win
this.iObserver.update(this.tries < this.triesLimit &&
this.goalWord.equals(this.currentWord));
}
}
Your Main class
public class Main{
public static void main(String[] args) {
// PlayHangman (game status)
PlayHangman playHangman = new PlayHangman();
// Hangman initializes with a goalWord and the triesLimit
Hangman hangman = new Hangman("HangmanJava", 5);
// Set the observer
hangman.setObserver(playHangman);
// During the game you just can set the current word and add a try
// You're not setting the status directly, that's the magic of the Observer pattern
hangman.setCurrentWord("Hang");
hangman.addTry();
hangman.setCurrentWord("HangmanJava");
}
}
Hope this helps and enjoy Java

Related

How do you use methods from sub classes in the main class in Java?

I am working on an assignment and I can not figure out what to do. I have three different Java classes. And I am trying to use the methods in one class to do something in a different class. I am making a very primitive playlist program. I have to check to see if the playlist is full, if its not i have to ask the title and artist. Then I have to call my method using the title and artist as parameters. I was wondering if anyone could point me in the right direction as to what I had to do to call the method? I still don't completely understand loops either but i know that I have to use a for loop in order to do this. Thankyou for your time.
Here is my code:
Main Class
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
PlayList p = new PlayList (5);
Scanner sc = new Scanner(System.in);
String command;
String title;
String artist;
System.out.println("Enter a to add, r to remove, d to display,or q to
quit:");
command = sc.nextLine();
while (!command.equals("q")) {
// Interpret command
if (command.equals("a")) {
//add song
for (int i = 0; i <= PlayList.isFull(title, artist);i++) {
if(songs[i])== null {
songs[i] = filled;
}
}
} else if (command.equals("r")) {
// Remove a song
System.out.print("Title: ");
title = sc.nextLine();
p.remove(title);
} else if (command.equals("d")) {
// Fill this in
}
// Get the next command
System.out.println("Enter a to add, r to remove, d to display, or q to
quit:");
command = sc.nextLine();
}
System.out.println("Program Ended");
}
}
PlayList Class
public class PlayList {
private Song [] songs;
private int filled;
public PlayList (int size){
songs = new Song[size];
}
public boolean isFull() {
return (filled >= songs.length);
}
public void add(String t, String a) {
for (int i = 0; i < songs.length; i++){
if (songs[i] == null){
songs[i] = new Song(t,a);
filled++;
}
}
}
public void display() {
for (int i = 0; i < songs.length; i++){
if (songs[i] != null) {
System.out.println(songs[i]);
}
}
}
public void remove(String t) {
//return t?
for (int i = 0; i < songs.length; i--){
if (songs[i] == null){
songs[i] = null;
break;
}
}
}
}
Song Class
public class Song {
String title;
String artist;
public Song (String t, String a) {
title = t;
artist = a;
}
public String toString() {
return "Title: " + title + " " + "Artist: " + artist;
}
}
First of all you are using isFull function of class PlayList wrong.
for (int i = 0; i <= PlayList.isFull(title, artist);i++)
isFull is a no argument function, and you are using it with passing 2 arguments.
isFull function returns a boolean value (i.e. true/false), but you are comparing it with an int, which does not make any sense.
isFull is not a static function. Therefore you cannot use it directly with class name.
-either you will need to declare function isFull as static.
public static boolean isFull()
-or you will need to create an object of class PlayList in class Main and then call the java function using that java object.
Also, your Function remove is not performing any task
if (songs[i] == null){
songs[i] = null;
}
It is checking if songs[i] is already null and then it sets it back to null, which does not make any sense.
And you should increment i (i.e. i++) not decrement it (i.e. i--)
for (int i = 0; i < songs.length; i--)
If you want to call method from another class that method must be a static method. Then you can call it using Class name and Method name.
For an example;
public class main(){
A a = new A();
a.x();
}
public class A{
public static void x(){};
}
You called isFull method with two parameters but your PlayList class does not have any parameter for isFull method. That is an error.
I re-write your assignment class set using ArrayList for PlayList class. Follow this codes. Hope you can understand it's concept of OOP(Follow this tutorials. https://www.javatpoint.com/java-oops-concepts).
Main Class
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
PlayList p = new PlayList (5);
Scanner sc = new Scanner(System.in);
String command;
String title;
String artist;
System.out.println("Enter a to add, r to remove, d to display,or q to quit:");
command = sc.nextLine();
while (!command.equals("q")) {
// Interpret command
if (command.equals("a")) {
//add song
System.out.println("Enter Title:");
title = sc.nextLine();
System.out.println("Enter Artist:");
artist = sc.nextLine();
if(!p.isFull()) {
p.add(title, artist);
System.out.println("Added Success!");
}
else
System.out.println("Sorry,Playlist is full");
} else if (command.equals("r")) {
// Remove a song
System.out.print("Title: ");
title = sc.nextLine();
p.remove(title);
} else if (command.equals("d")) {
// Fill this in
p.display();
}
// Get the next command
System.out.println("Enter a to add, r to remove, d to display, or q to quit:");
command = sc.nextLine();
}
System.out.println("Program Ended");
}
}
PlayList Class
import java.util.ArrayList;
import java.util.List;
public class PlayList {
private static List<Song> songs;
private static int filled;
private static int size = 0;
public PlayList (int s){
songs = new ArrayList<>();
size = s;
}
public static boolean isFull() {
return (filled == size);
}
public static void add(String t, String a) {
songs.add(new Song(t,a));
filled++;
}
public void display() {
for (int i = 0; i < songs.size(); i++){
if (songs.get(i) != null) {
System.out.println(songs.get(i));
}
}
}
public void remove(String t) {
//return t?
for (int i = 0; i < songs.size(); i++){
if (songs.get(i).title == t){
songs.remove(i);
break;
}
}
}
public static int getSize(){
return songs.size();
}
}
Song Class is same as you wrote.

Subclass final method not being called

I don't get what's going on here, but the final method
s.castable()
that overrides the motherclass's namesake abstract method doesn't get called.
Here is where I try to call s.castable():
public void cast(String[] request) {
System.out.println("cast called");
if (this.session.getPlayer()==this.game.getTurnPlayer()) {
System.out.println("first condition passed");
Spell s = this.session.getPlayer().getCharacter().getSpells().get(Integer.valueOf(request[1]));
ArrayList<String> usernames = new ArrayList();
System.out.println("Now printing spell: "+s);
for (int i = 6; i < request.length; i++) {
usernames.add(request[i]);
}
System.out.println("username create.d");
if (s.castable()) { //HERE
System.out.println("Second condition passed");
s.cast(Integer.valueOf(request[1]), Integer.valueOf(request[2]),request[3].charAt(0), request[4].charAt(0), usernames);
String str = "";
for (String st : usernames) {
str += st;
}
this.session.send("YOUSPELL "+request[1]+" "+request[2]+" "+request[3]+" "+request[4]+" "+str);
System.out.println("Done");
}
}
}
Here is the "Spell" MotherClass:
public abstract class Spell {
private int manaCost;
private int coolDown;
private int range;
private Player player;
public abstract void cast(int x, int y, char mode1, char mode2,ArrayList<String> usernames);
public abstract Boolean castable();
//Then all getters and setters.
}
And here is the final class "Velocity":
public final class Velocity extends Spell {
private final int manaCost;
private final Player player;
private final int coolDown;
private final int coolDownTime;
private final int additionalMovement;
private final int spellRef;
private final ArrayList<String> usernames = new ArrayList();
public Velocity(Player p) {
this.spellRef = 0;
this.additionalMovement = 5;
this.player = p;
this.manaCost = 5;
this.coolDownTime = 3;
this.coolDown = 0;
super.setCoolDown(coolDown);
super.setManaCost(manaCost);
super.setPlayer(p);
}
#Override
public final void cast(int x, int y, char mode1, char mode2,ArrayList<String> usernames) {
System.out.println("Velocity casted.");
player.setMovement(player.getMovement() + additionalMovement);
setCoolDown(coolDownTime);
}
#Override
public final Boolean castable() {
System.out.println(player.getMana());
System.out.println(manaCost);
System.out.println(getCoolDown());
if (player.getMana() >= manaCost && getCoolDown() >= 0) {
return true;
}
return false;
}
}
Finally, the console output:
cast called
first condition passed
Now printing spell: model.haraka.be.Velocity#739bb60f
username create.d.
As you can see the spell object is known.
Can you help me ?
Thank you
The only possible problem here can be that Abstract class Spell's variable s doesn't contain the reference to Velocity object.
hence the castable method of velocity class never gets called.
If the castable method is returning false as mentioned by many
people System.out.println() statements must be printed which is not
the case I think.
But to be sure this is the problem, Please explain:
Spell s = this.session.getPlayer().getCharacter().getSpells().get(Integer.valueOf(request[1]));
What are below methods return type ?
getPlayer()
getSpells()
get(Integer.valueOf(request[1])
This is too much to ask/comment in comment section hence posting as an answer.

Java error - invalid method declaration; return type required

I'm trying to complete this java program, but every time I try to compile it I get this error. Can someone figure out why my program is doing this. It seems that no matter what I do I still happen to get an error on my program. I tried everything I know to see if it would work. Please someone help me.
import java.util.Scanner;
public class Period
{
private static String phrase;
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
String userInput;
int[] letter = new int [27];
int number = keyboard.nextInt();
System.out.println("Enter a sentence with a period at the end.");
userInput = keyboard.nextLine();
userInput.toLowerCase();
}
// this is where the error is occuring at.
public Sorter(String newPhrase)
{
phrase=newPhrase.substring(0,newPhrase.indexOf("."));
}
private int charToInt(char currentLetter)
{
int converted=(int)currentLetter-(int)'a';
return converted;
}
private void writeToArray()
{
char next;
for (int i=0;i<phrase.length();i++)
{
next=(char)phrase.charAt(i);
sort(next);
}
}
private String cutPhrase()
{
phrase=phrase.substring(0,phrase.indexOf("."));
return phrase;
}
private void sort(char toArray)
{
int placement=charToInt(toArray);
if (placement<0)
{
alphabet[26]=1;
}
else
{
alphabet[placement]=alphabet[placement]+1;
}
}
public void entryPoint()
{
writeToArray();
displaySorted();
}
private void displaySorted()
{
for (int q=0; q<26;q++)
{
System.out.println("Number of " + (char)('a'+q) +"'s: "+alphabet[q]);
}
}
}
The 'Sorter' method is missing a return type. It should be:
public void Sorter(String newPhrase)
{
phrase = newPhrase.substring(0, newPhrase.indexOf("."));
}
The method is not called anywhere, so i am not sure if this is what you intended it to do.
add the void return type:
public void Sorter(String newPhrase) // HERE
{
phrase=newPhrase.substring(0,newPhrase.indexOf("."));
}
There are a lot of errors in the above code - see below for some code that runs, though i can't be sure it does exactly what you want given the limited scope of the question.
I don't want to stray too far from the original question, but you should really consider using instance variables and encapsulating your data, rather than relying on static variables.
import java.util.Scanner;
public class Period
{
private static String phrase;
private static int[] alphabet = new int [27];
public static void main(String [] args)
{
System.out.println("Enter a sentence with a period at the end.");
Scanner keyboard = new Scanner(System.in);
phrase = keyboard.nextLine().toLowerCase();
Period period = new Period();
period.entryPoint();
}
public void Sorter(String newPhrase)
{
phrase = newPhrase.substring(0,newPhrase.indexOf("."));
}
private int charToInt(char currentLetter)
{
int converted=(int)currentLetter-(int)'a';
return converted;
}
private void writeToArray()
{
char next;
for (int i=0;i<phrase.length();i++)
{
next=(char)phrase.charAt(i);
sort(next);
}
}
private String cutPhrase()
{
phrase=phrase.substring(0,phrase.indexOf("."));
return phrase;
}
private void sort(char toArray)
{
int placement=charToInt(toArray);
if (placement<0)
{
alphabet[26]=1;
}
else
{
alphabet[placement]=alphabet[placement]+1;
}
}
public void entryPoint()
{
writeToArray();
displaySorted();
}
private void displaySorted()
{
for (int q=0; q<26;q++)
{
System.out.println("Number of " + (char)('a'+q) +"'s: "+alphabet[q]);
}
}
}

An Arraylist of Arrays or os there a better way?

So thanks to the wonderful people here i've managed to get something semi workable, still have a couple bugs but maybe you guys can help me figure it out. So far none of the solution provided were a exact match (which is why i havent up voted them) but they did help me look at things in a new way and get things moving forward. So here is the current problem.
First the code then the explination
RaceButtons[RaceCounter] = new JToggleButton();
RaceButtons[RaceCounter].setIcon(RCiconSM);
RaceButtons[RaceCounter].setBorder(BorderFactory.createEmptyBorder());
RaceButtons[RaceCounter].setContentAreaFilled(false);
RaceButtons[RaceCounter].setActionCommand(temp_race.getRaceNameString(RaceCounter));
RaceButtons[RaceCounter].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
Race race = new Race(1, 1, GenderList[PHYSICAL_SEX]);
race.setRaceID(race.getRaceIDFromString(ae.getActionCommand()));
//System.out.println(race.getraceID());
if (RaceButtons[race.getraceID()].isSelected()){
RaceButtons[race.getraceID()].setBorderPainted(true);
RaceButtons[race.getraceID()].setBorder(new LineBorder(Color.blue,2));
MyRaceArray.add(new Race(race.getraceID(), 1, GenderList[PHYSICAL_SEX]));
}else{
RaceButtons[race.getraceID()].setBorderPainted(false);
};
So first i create an array of Toggle buttons and when you click it it draw the border and then getting it's info i can add it to the array for races but this lives me with another problem i cant quite figure the logic off. Namly if there are already selected button it adds another instances to the button, it shouldn't do that it should ignore iexaisting entries but that means i have to check the arry for a matching object of type Race withthe same info right? What's the best way to do that?
And when you deselect it how do i remove that same object.
This is how your code should look like with a Race class:
import java.util.ArrayList;
import java.util.List;
public class Race {
private int raceID;
private double purity;
private int strMod;
private int dexMod;
private int conMod;
private int wisMod;
public int getRaceID() {
return raceID;
}
public void setRaceID(int raceID) {
this.raceID = raceID;
}
public double getPurity() {
return purity;
}
public void setPurity(double d) {
this.purity = d;
}
public int getStrMod() {
return strMod;
}
public void setStrMod(int strMod) {
this.strMod = strMod;
}
public int getDexMod() {
return dexMod;
}
public void setDexMod(int dexMod) {
this.dexMod = dexMod;
}
public int getConMod() {
return conMod;
}
public void setConMod(int conMod) {
this.conMod = conMod;
}
public int getWisMod() {
return wisMod;
}
public void setWisMod(int wisMod) {
this.wisMod = wisMod;
}
#Override
public String toString() {
return "Race [raceID=" + raceID + ", purity=" + purity + ", strMod="
+ strMod + ", dexMod=" + dexMod + ", conMod=" + conMod
+ ", wisMod=" + wisMod + "]";
}
public static void main(String args[]) {
//create a list of race objects
List<Race> raceCollection = new ArrayList<Race>();
//create a race object
Race race = new Race();
race.setRaceID(1);
race.setPurity(0.75);
race.setStrMod(5);
race.setDexMod(7);
race.setConMod(-2);
race.setWisMod(3);
//add race object to collection
raceCollection.add(race);
//You can create and add multiple objects of race to the collection
//Iterate your list and print the objects
for(Race raceObj:raceCollection) {
System.out.println(raceObj);
}
}
}
You will be able to make it work using an ArrayList of arrays, but that possibly isn't the best way in the long run. It can be very fiddly and error-prone to deal with - what happens when you insert a new race or attribute, but forget to to change the index somewhere?
Arrays and ArrayLists are usually best reserved for situations where you actually have a sequence / list (often with a meaningful sequence order).
In your case I'd be more inclined to adopt a prototype model. Typically in Java you would represent each race with a HashMap (or a data structure containing a HashMap), there the map represents the relationship between the "Attribute ID" and the "Default Value".
Creating a new elf is then just a case of initialising the elf's attributes using the default values from his race (or a average of different races, if you want...)
Some people may suggest making an OOP class with lots of named fields. This can also work, but IMHO a prototype model is better - it gives you much more flexibility in the long run. You often want to process large groups of attributes in the some way, and doing this is pretty messy if you have to refer to each of the attribute fields individually.
import java.util.ArrayList;
import java.util.List;
public class Race
{
private final int raceID;
private final double purity;
private final int strMod;
private final int dexMod;
private final int conMod;
private final int wisMod;
public Race (int raceID, double purity, int strMod, int dexMod, int conMod, int wisMod)
{
this.raceID = raceID;
this.purity = purity;
this.strMod = strMod;
this.dexMod = dexMod;
this.conMod = conMod;
this.wisMod = wisMod;
}
public int getRaceID ()
{
return raceID;
}
public double getPurity ()
{
return purity;
}
public int getStrMod ()
{
return strMod;
}
public int getDexMod ()
{
return dexMod;
}
public int getConMod ()
{
return conMod;
}
public int getWisMod ()
{
return wisMod;
}
#Override public String toString ()
{
return "RaceID:" + raceID
+ " purity:" + purity
+ " strMod:" + strMod
+ " dexMod:" + dexMod
+ " conMod:" + conMod
+ " wisMod:" + wisMod;
}
#override public int hashCode ()
{
return raceID;
}
#override public boolean equals (Race r)
{
return (r != null && this.raceID == r.getRaceID());
}
#override public Object clone ()
{
return new Race(this.raceID,this.purity,this.strMod,this.dexMod,this.conMod,this.wisMod);
}
public static void main(String args[])
{
// simple test
ArrayList<Race> races = new ArrayList<Race>();
Race a = new Race(0,0.5,1,2,3,4);
Race b = new Race(1,0.75,2,3,4,5);
Race c = new Race(2,0.25,-1,-2,-3,-4);
races.add(a);
races.add(b);
races.add(c);
for(Race race : races)
{
// System.out.println(race.toString());
System.out.println(race);
}
}
}
Then we have the visual model, which can be handled like this:
class RacePanel implements ActionListener
{
private Map<Integer,JToggleButton> r;
private Map<Integer,Race> f;
public RacePanel()
{
r = new TreeMap<Integer,JToggleButton>();
f = new TreeMap<Integer,Race>();
}
public JToggleButton add (Race a)
{
JToggleButton button = new JToggleButton();
button.setIcon(RCiconSM);
button.setBorder(BorderFactory.createEmptyBorder());
button.setContentAreaFilled(false);
button.setActionCommand(a.getRaceID());
button.addActionListener(this);
r.put(a.getRaceID, button);
f.put(a.getRaceID, a);
}
public void remove (int raceID)
{
r.remove(a.getRaceID);
f.remove(a.getRaceID);
}
// When a button is clicked
public void actionPerformed(ActionEvent e)
{
// related race
Race a = f.get(e.getActionCommand());
// clicked button
JToggleButton b = r.get(e.getActionCommand());
// ..
}
public ArrayList<JToggleButton> getButtonList ()
{
return new ArrayList<Value>(r.values());
}
public ArrayList<Race> getRaceList ()
{
return new ArrayList<Value>(f.values());
}
public Race getRace (int raceID)
{
return f.get(raceID);
}
public JToggleButton getButton (int raceID)
{
return r.get(raceID);
}
// ..
}

How do I access a variable of one class in the function of another class?

I'm having a class Main (which has public static void main(String []args))and another class MyDocument.
There is a variable text present in the Main class which I want to access from a function alphabetOccurrence() present in the MyDocument class. How do I do this? I don't want to use it as a static variable. And any changes can be done only in the function, rest of the code should be untouched.
import java.util.*;
class Main {
public static void main(String[] args) {
MyDocument document = null;
String text;
text = "good morning. Good morning Alexander. How many people are there in your country? Do all of them have big houses, big cars? Do all of them eat good food?";
char letter = 'd';
document = new MyDocument();
document.setDocumentText(text);
System.out.println("Letter " + letter + " has occured "
+ document.alphabetOccurrence(letter) + " times");
}
}
class MyDocument {
private ArrayList<Character> document = new ArrayList();
public MyDocument() {
}
void setDocumentText(String s) {
for (int i = 0; i < s.length(); i++)
document.add(s.charAt(i));
}
ArrayList getDocumentText() {
return this.document;
}
public int alphabetOccurrence(char letter) {
// use text variable here..
}
}
You should change your MyDocument class to add new String field to hold text:
import java.util.ArrayList;
class MyDocument {
private String text;
private ArrayList<Character> document = new ArrayList();
public MyDocument() {
}
void setDocumentText(String s) {
this.text = text;
for (int i = 0; i < s.length(); i++)
document.add(s.charAt(i));
}
ArrayList<Character> getDocumentText() {
return this.document;
}
public int alphabetOccurrence(char letter) {
this.text; //do something
}
}
you could pass variable text as a parameter in your function
public int alphabetOccurrence(char letter, String text){
String text2 = text;
// use text variable here...
}

Categories

Resources