import java.util.ArrayList;
public class Folder extends AbstractFile
{
//Replace previous ArrayLists with a single
//ArrayList of AbstractFile references
private ArrayList<AbstractFile> files = new ArrayList();
AbstractFile abstractfile;
/**
* Constructor for objects of class Folder
*/
public Folder(String name)
{
super();
this.name = name;
}
// replace previous add methods
// with a single add(AbstractFile fileObject) method
public boolean add(AbstractFile fileObject)
{
return files.add(fileObject);
}
#Override
public int size()
{
int size =0; // size holds the running total
for (AbstractFile file : files){ // for each AbsFile ref
size+=file.size(); //call size() and update the running total
}
return size; // return the final value
}
#Override
public int getNumFiles(){
int numFiles = 0;
for(AbstractFile file: files)
{
numFiles += file.getNumFiles();
}
return numFiles;// default value
}
#Override
public int getNumFolders(){
int numFolders = 0;
// for(AbstractFile file: files)
// {
// if(file instanceof Folder)
// {
// numFolders += file.getNumFolders();
// }
// }
// return numFolders;// default value
for (Object e : files)
{
if (e instanceof Folder)
{
numFolders += e.getNumFolders();
}
}
return numFolders;// default value
}
#Override
public AbstractFile find(String name){
//TODO Later - not in mini assignment
return null;
}
}
AbstractFile Class
public abstract class AbstractFile
{
// instance variables -
String name;
public abstract int size();
public abstract int getNumFiles();
public abstract int getNumFolders();
public abstract AbstractFile find(String name);
public String getName(){
return name;
}
}
FileSystem Class- for testing
public class FileSystem
{
public static void main(String[] args)
{
FileSystem fileSystem = new FileSystem();
fileSystem.fileTest1();
}
public void fileTest1(){
Folder documents = new Folder("Documents");
Folder music = new Folder("Music");
Folder photos = new Folder("Photos");
documents.add(music);
documents.add(photos);
File assign1 = new File("assign1.doc");
documents.add(assign1);
Folder dylan = new Folder("Dylan");
music.add(dylan);
Folder band = new Folder("The Band");
music.add(band);
File family = new File("family.jpg");
photos.add(family);
File tambourine = new File("tambourine.mp3");
dylan.add(tambourine);
File dixie = new File("dixie.mp3");
band.add(dixie);
File weight = new File("weight.mp3");
band.add(weight);
String contents1 = ("Hey, mister, can you tell me ");
String contents2 = ("Hey Mr Tambourine Man");
String contents3 = ("The night they drove old dixie down");
String contents4 = ("fee fi fo fum");
weight.setContents(contents1); // add contents to each File
tambourine.setContents(contents2);
dixie.setContents(contents3);
assign1.setContents(contents4);
//********test for size()****************
int expected = contents1.length() + contents2.length() + contents3.length() + contents4.length();
int result = documents.size();
if(result==expected){ // test fro equality
System.out.println("size() works");
}else{
System.out.println("size() doesn't work");
}
//*****************************************
//*****************test for getNumFiles()******************
expected =5;// what value should expected be set to?
result = documents.getNumFiles();
if(result==expected){ // test fro equality
System.out.println("NumFiles() works");
}else{
System.out.println("NumFiles() doesn't work");
}
//output the results of the test for equality
// **************************************
//*****************test for getNumFiles()******************
expected = 5; // what value should expected be set to?
result = documents.getNumFolders();
if(result==expected){ // test fro equality
System.out.println("NumFolder() works");
}else{
System.out.println("NumFolder() doesn't work");
System.out.printf("%d",result);
}
// **************************************
}
}
File Class
public class File extends AbstractFile
{
private String contents;
/**
* Constructor for objects of class File
*/
public File(String name)
{
super();
this.name = name;
}
public String getContents(){
return contents;
}
public void setContents(String contents){
this.contents = contents;
}
#Override
public int size()
{
if(contents==null){ //handle situation where contents may not have been set
return 0;
}
return contents.length();
}
#Override
public int getNumFiles(){
return 1; // a File object just returns 1 (it contains one File - itself)
}
#Override
public int getNumFolders(){
//TODO
return 0;
}
#Override
public AbstractFile find(String name){
//TODO Later - not in mini assignment
return null;
}
}
Hi, So Basically I'm having trouble with the getNumFolders(method) I have a test class created with 5 folders and these are stored in an ArrayList of type AbstractFile called files. I am trying to loop through this ArrayList to count the folders, bare in mind this ArrayList also contains files, so they must not be counted.
I would appreciate any help.
Thanks so much!
Simply if you want to count the number of Folder instances, then below should do the work.
public int getNumFolders() {
int numFolders = 0;
for(AbstractFile file: files) {
if(file instanceof Folder) {
numFolders++;
}
}
return numFolders;
}
and expectedValue should be 2 here accroding to your test case.
in fileTest1() method of your test case,
expected = 2; // this should be two because there are two folders called music and photos in documents folder
result = documents.getNumFolders();
Related
I'm trying to create a class that will do everything that a different class can do, but it will use random integers in order to create the objects that would normally require user input. Here I have a Pokemon program where I have class where the user creates a Pokemon trainer by inputting their name, and the program will create an ArrayList where the trainer's Pokemon are stored. I have a subclass called ComputerTrainer where it should have the same functionality, but randomly generated Pokemon will be added to the trainer's list of Pokemon. I created a constructor that accesses the protected variables in the PokemonTrainer class, but I'm getting an error that says "reason: actual and formal argument lists differ in length". Why I am getting this error?
Here is the code for the PokemonTrainer class:
import java.util.ArrayList;
public class PokemonTrainer
{
// private constants
private static final int MAX_POKEMON = 2;
protected ArrayList<Pokemon> pokemonList;
protected String name;
protected int numOfPokemon;
// Write your PokemonTrainer class here
public PokemonTrainer(String name)
{
this.name = name;
pokemonList = new ArrayList<Pokemon>();
}
public boolean addPokemon(Pokemon p)
{
if(numOfPokemon < MAX_POKEMON)
{
pokemonList.add(p);
numOfPokemon++;
return true;
}
else
{
return false;
}
}
public boolean hasLost()
{
int numOfPokemonThatLost = 0;
for(Pokemon p : pokemonList)
{
if(p.hasFainted())
{
numOfPokemonThatLost++;
}
}
if(numOfPokemonThatLost == numOfPokemon)
{
return true;
}
else
{
return false;
}
}
public Pokemon getNextPokemon()
{
int nextPokemon = 0;
int numOfPokemonThatLost = 0;
for(Pokemon p : pokemonList)
{
while(p.hasFainted() && nextPokemon < numOfPokemon)
{
nextPokemon++;
numOfPokemonThatLost++;
if(nextPokemon < numOfPokemon)
{
p = pokemonList.get(nextPokemon);
}
}
}
if(numOfPokemonThatLost == numOfPokemon)
{
return null;
}
else
{
return pokemonList.get(nextPokemon);
}
}
public Pokemon getPokemon(int nPokemon)
{
return pokemonList.get(nPokemon);
}
public int getNumberOfPokemons()
{
return pokemonList.size();
}
public static int getMaxPokemon()
{
return MAX_POKEMON;
}
public String toString()
{
return name;
}
}
and here is the code for the ComputerTrainer subclass:
import java.util.ArrayList;
import java.util.Random;
public class ComputerTrainer extends PokemonTrainer
{
// private constants
// Possible pokemon names and move names to generate random Pokemon
private static final String[] POKEMON_NAMES = {"Pikachu", "Bulbasaur", "Charmander", "Squirtle"};
private static final String[] MOVE_NAMES = {"Tailwhip", "Bodyslam", "Splash", "Shock"};
private static final int MAX_DAMAGE = 25;
private static final int MAX_MOVES = 4;
private PokemonImages images = new PokemonImages();
// Write a Constructor that sets the name of the ComputerTrainer
// and adds 2 randomly generated Pokemon to itself
public ComputerTrainer(String name)
{
this.name = name;
pokemonList = new ArrayList<Pokemon>();
for(int i = 0; i < PokemonTrainer.getMaxPokemon(); i++)
{
Random num = new Random();
int randomNumber = num.nextInt(POKEMON_NAMES.length);
Pokemon p = new Pokemon (POKEMON_NAMES[randomNumber], images.getPokemonImage(POKEMON_NAMES[randomNumber]));
pokemonList.add(p);
numOfPokemon++;
}
}
/*
* Adds a randomly generated Pokemon to this ComputerTrainer's
* collection of Pokemon. A ComputerTrainer can only have 2
* Pokemon. This method returns true if there was room for the
* new Pokemon and it was successfully added, false otherwise.
*/
public boolean addRandomPokemon()
{
if(numOfPokemon < PokemonTrainer.getMaxPokemon())
{
Random num = new Random();
int randomNumber = num.nextInt(POKEMON_NAMES.length);
Pokemon p = new Pokemon (POKEMON_NAMES[randomNumber], images.getPokemonImage(POKEMON_NAMES[randomNumber]));
pokemonList.add(p);
numOfPokemon++;
return true;
}
else
{
return false;
}
}
// Returns a Move randomly chosen from the set of Moves
// that this trainer's current Pokemon knows.
// If all Pokemon have fainted, returns null.
public Move chooseRandomMove()
{
Pokemon currentBattlingPokemon = getNextPokemon();
// This method isn't finished yet
}
}
The program outputs the following error:
ComputerTrainer.java:20: error: constructor PokemonTrainer in class PokemonTrainer cannot be applied to given types;
{
^
required: String
found: no arguments
reason: actual and formal argument lists differ in length
The problem is that PokemonTrainer only has a constructor that has one String as parameter:
public class PokemonTrainer
{
public PokemonTrainer(String name) {
...
}
but you are not calling that constructor from ComputerTrainer:
public class ComputerTrainer extends PokemonTrainer
{
public ComputerTrainer(String name) {
this.name = name;
...
}
}
Java does not automatically call the constructor of the superclass that matches the actual constructor, it calls the default (parameter-less constructor) but the superclass does not have it.
Solution: add an explicit invokation of the correct constructor of the superclass:
public class ComputerTrainer extends PokemonTrainer
{
public ComputerTrainer(String name) {
super(name);
...
}
}
see Java Language Specification 8.8.7. Constructor Body for more details
Note: the error message is a bit confusing since there is like a hidden super() call as first statement in the ComputerTrainer constructor
I need some help please: I'm making a flight roster simulation in java. The roster will hold 25 passengers, 22 of which come from a text file (PassengerList.txt). For each passenger there are 3 required data points; name, seat class & seat # and 2 optional data points frequent flyer number & frequent flyer points. Each passenger is on its own line and each data point is separated by a comma. For example:
Allen George,Economy Class,8A,#GEO456,10000
Judy Hellman,Economy Class,8B
I have this class, along with constructor so far:
public class Passengers
{
private String name, type, seat, flyernum;
private int points;
//Constructor to intialize the instance data
Passengers(String full_name, String seat_type, String seat_number,
String frequent_flyer_number, int frequent_flyer_points)
{
name=full_name;
type=seat_type;
seat=seat_number;
flyernum=frequent_flyer_number;
points=frequent_flyer_points;
} //end Passengers
What I need to do is to read each line from the text file and create the array, i.e. make the first look line look something like this:
Passenger passenger1 = new Passenger ("Allen George","Economy Class","8A"
,"#GEO456",10000)
Into an array like this:
Passenger[0] = passenger1;
I am obviously a java beginner, but I have been caught up on this for so long and I keep getting different error message after error message when I try something new. I have been using Scanner to read the file. The text file does not need to be overwritten, just read and scanned by the program. Only Arrays can be used as well, ArrayList is a no go. Only two files too, the Passengers class and the main method. Please help! Thank you!
You can do it as bellow :
First you need a Passenger.class. It would look something like this (Note that I have added a toString():
public class Passenger {
private String name, type, seat, flyernum;
private int points;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getSeat() {
return seat;
}
public void setSeat(String seat) {
this.seat = seat;
}
public void setFlyernum(String flyernum) {
this.flyernum = flyernum;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
#Override
public String toString() {
return "Passenger{" +
"name='" + name + '\'' +
", type='" + type + '\'' +
", seat='" + seat + '\'' +
", flyernum='" + flyernum + '\'' +
", points=" + points +
'}';
}
}
Now for getting the passenger details from the file, I have create GetPassengerDetails.class, it handles reading in the data from the CSV file and allocating the right values for each Passenger.
public class GetPassengerDetails{
/** Reads the file one line at a time. Each line will is that split up and translated into a Passenger object */
public List<Passenger> getPassengersFromFile(BufferedReader reader) throws IOException {
List<Passenger> passengers = new ArrayList<>();
String line;
while ((line = reader.readLine()) != null) {
String[] passengerDetails = line.trim().split(",");
Passenger passenger = new Passenger();
for (int i = 0; i < passengerDetails.length; i++) {
SetPassengerName(passengerDetails, passenger, i);
setPassengerFlightType(passengerDetails, passenger, i);
setPassengerSeatNumber(passengerDetails, passenger, i);
SetPassengerFlyerNumber(passengerDetails, passenger, i);
setPassengerPoints(passengerDetails, passenger, i);
}
passengers.add(passenger);
}
return passengers;
}
private void setPassengerPoints(String[] passengerDetails, Passenger passenger, int i) {
if(i< passengerDetails.length && i == 4) {
passenger.setPoints(Integer.parseInt(String.valueOf(passengerDetails[4])));
}
}
private void SetPassengerFlyerNumber(String[] passengerDetails, Passenger passenger, int i) {
if(i< passengerDetails.length && i == 3) {
passenger.setFlyernum(String.valueOf(passengerDetails[3]));
}
}
private void setPassengerSeatNumber(String[] passengerDetails, Passenger passenger, int i) {
if(i< passengerDetails.length && i == 2) {
passenger.setSeat(String.valueOf(passengerDetails[2]));
}
}
private void setPassengerFlightType(String[] passengerDetails, Passenger passenger, int i) {
if(i< passengerDetails.length && i == 1) {
passenger.setType(String.valueOf(passengerDetails[1]));
}
}
private void SetPassengerName(String[] passengerDetails, Passenger passenger, int i) {
if(i< passengerDetails.length & i == 0) {
passenger.setName(String.valueOf(passengerDetails[i]));
}
}
}
Here is the main method to test the above code :
public class Main {
public static void main(String[] args) throws IOException {
String fileName = "resources/passengers.csv";
BufferedReader reader = new BufferedReader(new FileReader(fileName));
GetPassengerDetails passengerDetails = new GetPassengerDetails();
List<Passenger> passengers = passengerDetails.getPassengersFromFile(reader);
// For Testing Purposes lets get the Passengers
for (Passenger passenger : passengers
) {
System.out.println(passenger.toString());
}
}
}
After running the main method, this is the result that you will get :
Use this main method to read data from text files and converge data into the Passengers object. The whole list of passengers in passengersList objec.
public static void main(String[] args) {
List<Passengers> passengersList = new ArrayList<Passengers>();
File file = new File("Your file location..");
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while ((st = br.readLine()) != null){
String[] data = st.split(",");
String flyNumber = null;
int flyPoints = 0;
switch (data.length){
case 4: flyNumber = data[3];
break;
case 5: flyNumber = data[3];
flyPoints = Integer.valueOf(data[4]);
break;
}
Passengers passenger = new Passengers(data[0], data[1], data[2], flyNumber, flyPoints);
passengersList.add(passenger);
}
System.out.println(passengersList.get(0));
} catch (IOException e) {
e.printStackTrace();
}
}
if anyone can help please ,
i have an issue assign the values from a text file to the class fields.
i have created a class called process and it has a fields like
private String agent;
private String request_type;
private String class_type;
private String num_of_seats;
private String arrivaltime;
my motive is to assign 1block in the file to agent separated by space another block to request type and so on...
say Agent3 R F 10 1 here Agent3 is going to be assign to agent and R going to assign to request_type F to class_type, 10 to num_of_seats,1 to arrivaltime
i am using arraylist to saveinput file (not compulsory i know this only thats y) and another arraylist to save the objects of my class.i am using substring method to assign the values manually is there any way instead of that so that i can simply take block which is seprated by space and do my job.
The input file(input.txt is )
Agent1 R F 2 0
Agent3 R F 10 1
Agent1 C F 1 4
Agent2 C B 2 1
Agent2 R B 10 0
................................................................................
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* #author Navdeep
*
*/
class Process
{
private String agent;
private String request_type;
private String class_type;
private String num_of_seats;
private String arrivaltime;
public Process()
{
setProcess("0", null, null, "0", "0");
}
public Process(String a, String b,String c,String d,String e)
{
setProcess(a,b,c,d,e);
}
public void setProcess(String a, String b,String c,String d,String e)
{
setAgent(a);
setRequest_type(b);
setClass_type(c);
setNum_of_seats(d);
setArrivaltime(e);
}
public void setAgent(String a){
agent = a;
}
public void setRequest_type(String b){
request_type = b;
}
public void setClass_type(String c)
{
class_type = c;
}
public void setNum_of_seats(String d) {
num_of_seats = d;
}
public void setArrivaltime(String e)
{
arrivaltime=e;
}
public String getAgent(){
return agent;
}
public String getRequest_type(){
return request_type ;
}
public String getClass_type()
{
return class_type;
}
public String getNum_of_seats() {
return num_of_seats ;
}
public String getArrivaltime()
{
return arrivaltime;
}
#Override
public String toString() {
return String.format("%s,%s,%s,%s,%s",getAgent(),getRequest_type(),getClass_type(),getNum_of_seats(),getArrivaltime());
}
}
public class main
{
public static void main(String[] args) throws FileNotFoundException
{
File temp = new File(args[0]);
Scanner sc = new Scanner(temp);
ArrayList<String> input = new ArrayList<String>();
while(sc.hasNext())
{
input.add(sc.nextLine());
}
List<Process> mylist = new ArrayList<Process>();
for (int i= 0; i <input.size();i++)
{
Process processobject = new Process();
processobject.setAgent(input.get(i).substring(0, 6));
processobject.setRequest_type(input.get(i).substring(7,8));
processobject.setClass_type(input.get(i).substring(9,10));
if(input.get(i).length() == 15)
{
processobject.setNum_of_seats(input.get(i).substring(11,13));
processobject.setArrivaltime(input.get(i).substring(14,15));
}
if(input.get(i).length() == 14)
{
processobject.setNum_of_seats(input.get(i).substring(11,12));
processobject.setArrivaltime(input.get(i).substring(13,14));
}
mylist.add(processobject); // fill arraylist with objects of my class
}
System.out.println("array list of the input from the file" + input);
System.out.println("\n \nobjects in my list"+ mylist);
}
}
the overall motive of my project is to sort the objects according to the field priorities.
If your objective is to create Process class instance then you can use the following code:
while(sc.hasNext())
{
String line = sc.nextLine();
String elements[] = line.split(" ");
Process processobject = new Process();
processobject.setProcess(elements[0],elements[1],elements[2],elements[3],elements[4]);
}
You can improve the your setProcess method by setting accessing directly class attributes with this reference. Also you can pass the same parameters to Process class constructor then you won't need setProcess method. Check the below code.
public Process(String agent, String request_type, String class_type, String num_of_seats, String arrivaltime) {
this.agent = agent;
this.request_type = request_type;
this.class_type = class_type;
this.num_of_seats = num_of_seats;
this.arrivaltime = arrivaltime;
}
Try this:
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource(configFileName).getFile());
input = new FileInputStream(someFilePath);
prop.load(input);
String someString=prop.getProperty("someString");
int someintValue=new Integer(prop.getProperty("someintValue"));
I know this must be a fundamental design problem because I clearly can't do this. I want to call the ownGrokk, ownTyce, etc methods from another class depending on the value of the integer assigned to OwnedSpirits(int). This in turn fills arrays.
The problem is, I do this multiple times, and doing it from another class it seems like I have to make a new object every time to pass the new int argument, and doing so resets the value of spiritInstance. And, since that resets to zero, the arrays don't fill properly. I try to print out my array values later and I get an "ArrayIndexOutOfBoundsException".
public class OwnedSpirits {
private int spiritTypeInt = 0;
public static int spiritInstance=0;
public static int[] spiritarray = new int[9];
public static String[] spiritName = new String[9];
public static int[] party = new int[3];
public OwnedSpirits(int spiritcall){
if(spiritcall == 1){
ownGrokk();
}
if(spiritcall == 2){
ownRisp();
}
if(spiritcall == 3){
ownTyce();
}
if(spiritcall == 4){
ownDaem();
}
if(spiritcall == 5){
ownCeleste();
}
}
private void ownGrokk(){
spiritName[spiritInstance] = "Grokk";
spiritInstance++;
}
private void ownRisp(){
spiritName[spiritInstance] = "Risp";
spiritInstance++;
}
private void ownDaem(){
spiritName[spiritInstance] = "Daem";
spiritInstance++;
}
private void ownCeleste(){
spiritName[spiritInstance] = "Celeste";
spiritInstance++;
}
private void ownTyce(){
spiritName[spiritInstance] = "Tyce";
spiritInstance++;
}
and this code is in another class, where it attempts to call the methods to fill the array
buttonConfirm.addListener(new ClickListener(){
#Override
public void clicked(InputEvent event, float x, float y) {
if(xcounter==3){
for(x=0; x<3; x++){
if(setdaemtrue == true){
new OwnedSpirits(4);
}
if(setrisptrue == true){
new OwnedSpirits(2);
}
if(setcelestetrue == true){
new OwnedSpirits(5);
}
if(settycetrue == true){
new OwnedSpirits(3);
}
if(setgrokktrue == true){
new OwnedSpirits(1);
}
}
}
}
});
and finally in yet another class:
System.arraycopy(OwnedSpirits.spiritName, 0, partylist, 0, 3);
#Override
public void show() {
System.out.println(partylist[0]);
System.out.println(partylist[1]);
System.out.println(partylist[2]);
spiritlist.setItems(partylist);
table.add(spiritlist);
table.setFillParent(true);
stage.addActor(table);
}
If the last part is confusing, it's because I am using libgdx. the print statements are there just to try to figure out why my list was having an error
I can show you what I would do to handle Spirits, and Parties.
The Spirit class, contains name and current party its assigned to:
package com.stackoverflow.spirit;
public class Spirit {
private String name;
private Party party;
private SpiritType type;
private static int id = 0;
public static enum SpiritType {
Grokk, Risp, Tyce, Daem, Celeste
};
public Spirit(String name, SpiritType type) {
create(name, type);
}
public Spirit(SpiritType type) {
create(null, type);
}
// This is to handle Java inexistance of default parameter values.
private void create(String name, SpiritType type)
{
Spirit.id++;
this.name = (name == null) ? (type.name() + " " + id) : name;
this.type = type;
}
public String getName() {
return name;
}
public Party getParty() {
return party;
}
public SpiritType getType() {
return type;
}
/**
* Used internally by #see Party
* #param party the party this Spirit belongs
*/
public void setParty(Party party) {
this.party = party;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString()
{
return this.name;
}
}
Finally the Party class, contains a set of Spirits, you can add and remove Spirits from the party.
package com.stackoverflow.spirit;
import java.util.HashSet;
public class Party {
private HashSet<Spirit> spirits = new HashSet<Spirit>();
private static int id = 0;
private String name = "Party " + Party.id++;;
public Party() {
}
public Party(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void add(Spirit spirit) {
if (!spirits.contains(spirit)) {
spirits.add(spirit);
if (spirit.getParty() != null) {
//Remove from previous party to update the other party set
spirit.getParty().remove(spirit);
}
spirit.setParty(this);
} else {
// throw new SpiritAlreadyOnParty();
}
}
public void remove(Spirit spirit)
{
if (spirits.contains(spirit))
{
spirit.setParty(null); // You could create a default empty party for "Nature/Neutral" Spirits perhaps :)
spirits.remove(spirit);
}
else {
//throw new SpiritNotInParty();
}
}
public boolean isOnParty(Spirit spirit) {
return spirits.contains(spirit);
}
public ArrayList<Spirit> getSpirits()
{
return new ArrayList<Spirit>(spirits);
}
public int getPartySize() {
return spirits.size();
}
public String getPartyInfo()
{
StringBuilder builder = new StringBuilder();
builder.append("Party:" + this.name + " Size:" + this.spirits.size() + "\n");
for (Spirit s : spirits)
{
builder.append(s.getName() + "\n");
}
return builder.toString();
}
#Override
public String toString()
{
return this.name;
}
}
Here I use the Spirit and Party classes, you could add more functionality, like properties for party strength, magic buffs on the party, etc:
package com.stackoverflow.spirit;
import com.stackoverflow.spirit.Spirit.SpiritType;
public class Main {
public static void main(String[] args) throws java.lang.Exception {
Party griffindor = new Party("Griffindor"), slytherin = new Party(
"Slytherin");
// You can also do for (SpiritType type : SpiritType.values() then
// type.ordinal()
for (int i = 0; i < SpiritType.values().length; i++) {
griffindor.add(new Spirit(SpiritType.values()[i]));
slytherin.add(new Spirit(SpiritType.values()[i]));
}
Spirit mySpirit = new Spirit("NotAHPFan", SpiritType.Celeste);
slytherin.add(mySpirit);
System.out.println("Name of party:" + mySpirit.getParty().getName());
System.out.println("Is on griffindor?:"
+ griffindor.isOnParty(mySpirit));
// What now?
griffindor.add(mySpirit);
System.out.println("Is " + mySpirit.getName() + " on "
+ slytherin.getName() + "?:" + slytherin.isOnParty(mySpirit));
System.out.println(mySpirit.getName() + " is now on "
+ mySpirit.getParty() + "\n");
System.out.println(griffindor.getPartyInfo());
System.out.println(slytherin.getPartyInfo());
}
}
P.D: I'm not a HP fan.
I have a problem that I can't get around how to solve, I'm currently working on a mini filesystem wich requiers to create an massive amount of objects (in theory). I currently tried ArrayList<INode> nodes = new ArrayList<INode>(); and then when I add an object(INode) nodes.add(new INodeDirectory(paths[i]));
But when I check later if this node excist in nodesit doesent, any suggestions on how to solve this or what to use instead?
MiniFs class:
package se.kth.id1020.minifs;
import edu.princeton.cs.introcs.StdOut;
import java.util.HashMap;
public class MiniFs implements FileSystem {
private final INodeDirectory root;
private HashMap<String,Integer> map = new HashMap<String, Integer>();
private int n = 0; //Number of objects created
priate ArrayList<INode> nodes = new ArrayList<INode>();
public MiniFs() {
root = new INodeDirectory("/");
map.put("/",n);
}
//Create a directory/folder
#Override
public void mkdir(String path) {
String paths[] = path.split("/");
if(paths.length == 2){
nodes.add(new INode<directory(paths[paths.length - 1]));
n++;
map.put(paths[1],n);
StdOut.println("OK.");
}
else{
for(int i = 1; i < paths.length; i++){
if(i == paths.length - 1){
if(map.containsKey(paths[i])){
StdOut.println("Directory already excists");
}
else{
nodes.add(new INodeDirectory(paths[i]));
n++;
map.put(paths[i],n);
StdOut.println("OK.");
}
}
else if(map.containsKey(paths[i]) == false){
throw new UnsupportedOperationException("Error: you have to create " + paths[i] + " first!");
}
}
}
}
//Create a file
#Override
public void touch(String path) {
String paths[] = path.split("/");
if(paths.length == 2){
nodes.add(new INodeFile(paths[paths.length - 1]));
n++;
map.put(paths[paths.length - 1], n);
StdOut.println("OK.");
}
else{
for(int i = 1; i < paths.length; i++){
if(i == paths.length - 1){
if(map.containsKey(paths[i])){
StdOut.println("File already excists");
}
else{
nodes.add(new INodeFile(paths[i]));
n++;
map.put(paths[i],n);
StdOut.println("OK.");
}
}
else if(map.containsKey(paths[i]) == false){
throw new UnsupportedOperationException("You have to create " + paths[i] + " first!");
}
}
}
}
//Create a pointer to a file or directory
#Override
public void ln (String path, String target){
String paths[] = path.split("/");
String targets[] = target.split("/");
if(paths.length == 2 && targets.length == 2 && map.containsKey(paths[1]) && map.containsKey(targets[1])){
int pathIndex = nodes.indexOf(paths[1]);
int targetIndex = nodes.indexOf(targets[1]);
nodes.get(pathIndex).setPointer(nodes.get(targetIndex));
StdOut.println("OK.");
}
}
}
INode class:
package se.kth.id1020.minifs;
public abstract class INode {
private String name;
private ArrayList<INode> pointer;
private long accessTime;
public INode(String name) {
this.name = name;
this.accessTime = System.currentTimeMillis();
}
public void setPointer(INode n) {
pointer.add(n);
}
public long getAccessTime() {
return accessTime;
}
public void setAccessTime(long accessTime) {
this.accessTime = accessTime;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
INodeDirectory class:
package se.kth.id1020.minifs;
public class INodeDirectory extends INode {
public INodeDirectory(String name) {
super(name);
}
}
INodeFile class:
package se.kth.id1020.minifs;
public class INodeFile extends INode {
public INodeFile(String name) {
super(name);
}
}
You need to override .equals() for anything that you're putting into an ArrayList and checking with .contains() or .indexOf().
It's very easy to get your IDE to help with this. I'd strongly recommend implementing .hashCode() as well, in case you want to use a HashMap later on (otherwise you'll hit a similar problem).
You have an even more serious problem, though, which is that when you check whether it's in there, you're passing a String to indexOf() rather than an INode. This will fail because the list doesn't store strings. If you want to check whether a node is there, you need to create a new node from the String, and check whether that's present.
You are trying to check if the ArrayList contains a certain instance of the INode class. However, you don't define how to compare tow INodes. ArrayList.contains() uses the INode class's default .equals() method, which will not actually work unless it is overriden using #Override in the INode class. If you are using Eclipse, you can easily generate the .equals() and .hashCode() functions by pressing Alt+Shift+S and selecting "Generate hashcode() and equals()