Saving ArrayList to Text File - java

I have been trying to get an ArrayList to save to a file. I can see it is creating the text file, but nothing is placed inside the text file, just blank.
Here is the main code with the ArrayList,Switch with option to save.
static int input, selection, i = 1;
static ArrayList<Animals> a;
// Main Method
public static void main(String[] args){
// Create an ArrayList that holds different animals
a = new ArrayList<>();
a.add(new Animals(i++, "Bear", "Vertebrate", "Mammal"));
a.add(new Animals(i++, "Snake", "Invertebrate", "Reptile"));
a.add(new Animals(i++, "Dog", "Vertebrate", "Mammal"));
a.add(new Animals(i++, "Starfish", "Invertebrates", "Fish"));
while (true) {
try {
System.out.println("\nWhat would you like to do?");
System.out.println("1: View List\n2: Delete Item\n3: Add Item\n4: Edit Item\n5: Save File\n0: Exit");
selection = scanner.nextInt();
if(selection != 0){
switch (selection) {
case 1:
ViewList.view();
Thread.sleep(4000);
break;
case 2:
Delete.deleteItem();
Thread.sleep(4000);
break;
case 3:
Add.addItem();
Thread.sleep(4000);
break;
case 4:
Edit.editItem();
Thread.sleep(4000);
break;
case 5:
Save.saveToFile("animals.txt", a);
Thread.sleep(4000);
break;
This is what I have written to handle file.
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
public class Save extends ALProgram{
public static void saveToFile(String fileName, ArrayList list){
Path filePath = Paths.get(fileName);
try{
System.out.println("File Saved");
Files.write(filePath, list, Charset.defaultCharset());
}catch(IOException e){
e.printStackTrace();
}
}
}
Here is Animal Class
class Animals {
public int id;
public String type, vertebrate, aclass;
public Animals(int id, String type, String vertebrate, String aclass) {
this.id = id;
this.type = type;
this.vertebrate = vertebrate;
this.aclass = aclass;
}
public int getID() {
return id;
}
public String getType() {
return type;
}
public String getVert() {
return vertebrate;
}
public String getaclass() {
return aclass;
}
}

There are two changes:
Your class need to implement CharSequence to be eligible to be passed to Files.write.
You need to over-ride toString method to specify how your contents look like when saved.
I can see output after above two changes.
class Animals implements CharSequence {
public int id;
public String type, vertebrate, aclass;
public Animals(int id,String type,String vertebrate,String aclass) {
this.id = id;
this.type = type;
this.vertebrate = vertebrate;
this.aclass = aclass;
}
public int getID() {
return id;
}
public String getType() {
return type;
}
public String getVert() {
return vertebrate;
}
public String getaclass() {
return aclass;
}
#Override
public int length() {
return toString().length();
}
#Override
public char charAt(int index) {
return toString().charAt(index);
}
#Override
public CharSequence subSequence(int start, int end) {
return toString().subSequence(start, end);
}
/* (non-Javadoc)
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
return "Animals [id=" + id + ", type=" + type + ", vertebrate=" + vertebrate + ", aclass=" + aclass + "]";
}
}

So, first one, you cannot just save it by casting it to string.
You need to get each element, build a string obly then write it down to file.
Here's an example:
public static void saveToFile(String fileName, ArrayList<Animal> list){
StringBuilder sb = new StringBuilder();
for(int i=0; i<=list.size(); i++) {
Animal lAn = list.get(i);
sb.Append("Animal ID: "+lAn.getID()+"; Animal type: "+lAn.getType()+"; Animal vert: "+lAn.getVert()+"; Animal aclass: "+lAn.getaclass()+"\r\n");
}
try (PrintStream out = new PrintStream(new FileOutputStream(fileName))) { out.print(sb.toString()); }
} catch(IOException e){ e.printStackTrace(); } }
Try it. Theres also could be some mistakes/mispelling because I wrote this code from my phone.

You could write only Iterable<? extends CharSequence>, so change you code like below.
Please make sure to override toString method of Animal class
List<Animal> animals = new ArrayList<>();
Animal a1 = new Animal(1L, "XYZ", "A2B");
Animal a2 = new Animal(2L, "ABC", "IJK");
animals.add(a1);
animals.add(a2);
List<String> strings = new ArrayList<>();
for (Animal animal : animals) {
strings.add(animal.toString());
}
Files.write(Paths.get("output.out"), strings, Charset.defaultCharset());

Related

Mapping fields of List to fields of a single Object

Suppose, I have a List of cats like this:
[Cat[name="Minnie", age=3], Cat[name="Pixie", age=1], Cat[name="Kazy", age=5]]
And an Object Cats with fields:
class Cats {
int MinnieAge;
int PixieAge;
int KazyAge;
}
What is the best way to map the ages to this Object? Preferably avoiding imperative approach and keeping it nice and clean. Is this possible with MapStruct or the streams API?
If you want to use streams you can start from implementing a collector:
public class CatsCollector implements Collector<Cat, Cats, Cats> {
#Override
public Supplier<Cats> supplier() {
return () -> new Cats();
}
#Override
public BiConsumer<Cats, Cat> accumulator() {
return (cats1, cat) -> {
switch (cat.name){
case "Minnie": cats1.minnieAge = cat.age; break;
case "Pixie": cats1.pixieAge = cat.age; break;
case "Kazy": cats1.kazyAge = cat.age; break;
}
};
}
#Override
public BinaryOperator<Cats> combiner() {
return (cats1, cats2) -> cats1;
}
#Override
public Function<Cats, Cats> finisher() {
return cats1 -> cats1;
}
#Override
public Set<Characteristics> characteristics() {
return Set.of(Characteristics.UNORDERED);
}
}
P.S. - Here a combiner is more like a stub because there are no requirements for combining logic provided.
P.P.S - There are also sort of assumptions to simplify access modifiers stuff.
Then if you have the model like this:
public class Cats {
int minnieAge;
int pixieAge;
int kazyAge;
#Override
public String toString() {
return "Cats{" +
"minnieAge=" + minnieAge +
", pixieAge=" + pixieAge +
", kazyAge=" + kazyAge +
'}';
}
}
You can use your custom collector:
public static void main(String[] args) {
List<Cat> cats = List.of(
new Cat("Minnie", 3),
new Cat("Pixie", 1),
new Cat("Kazy", 5));
Cats catsResult = cats.stream().collect(new CatsCollector());
System.out.println(catsResult);
}
I would define a Cat class with the attribute name and age. Then simply parse the input string into cat objects and store them in a list which already supports stream. See below example:
import java.util.*;
class Cat {
public String name;
public int age;
private Cat(String name, int age) { this.name = name; this.age = age;}
public String toString(){
return String.format("Cat[name=\"%s\", age=%d]",name,age);
}
public static List<Cat> parse(String input) {
List cats = new ArrayList();
int i = 0;
while (true) {
i = input.indexOf("name=", i);
if (i < 0) break;
String name = input.substring(i + 6, input.indexOf("\"", i + 7));
i = input.indexOf("age=", i);
int age = Integer.parseInt(input.substring(i + 4, input.indexOf("]", i)));
cats.add(new Cat(name, age));
}
return cats;
}
}
public class Main{
public static void main(String[] args) {
String input = "[Cat[name=\"Minnie\", age=3], Cat[name=\"Pixie\", age=1], Cat[name=\"Kazy\", age=5]]";
List<Cat> cats = Cat.parse(input);
cats.forEach(System.out::println);
cats.stream().filter(e->e.age > 4).forEach(System.out::println);
}
}
Output:
run:
Cat[name="Minnie", age=3]
Cat[name="Pixie", age=1]
Cat[name="Kazy", age=5]
Cat[name="Kazy", age=5]
BUILD SUCCESSFUL (total time: 0 seconds)

How can I use the indexOf() function to find an object with a certain property

I have an object, Pet, and one of the functions is to retrieve its name.
public class pet{
private String petName;
private int petAge;
public pet(String name, int age){
petName = name;
petAge = age;
}
public String getName(){
return petName;
}
public int getAge(){
return petAge;
}
}
I then have an ArrayList which holds a collection of pets as shown in the code below:
import java.util.ArrayList;
pet Dog = new pet("Orio", 2);
pet Cat = new pet("Kathy", 4);
pet Lion = new pet("Usumba", 6);
ArrayList<pet> pets = new ArrayList<>();
pets.add(Dog);
pets.add(Cat);
pets.add(Lion;
I was wondering how I could retrieve the index in the ArrayList or the object that has the name I need. So if I wanted to find out how old Usumba was, how would I do this?
Note: This is not my actual piece of code, it's just used so that I can better explain my problem.
Edit 1
So far, I have the following but I was wondering if there was a better or more efficient way
public int getPetAge(String petName){
int petAge= 0;
for (pet currentPet : pets) {
if (currentPet.getName() == petName){
petAge = currentPet.getAge();
break;
}
}
return petAge;
}
You can't use indexOf() for this purpose, unless you abuse the purpose of the equals() method.
Use a for loop over an int variable that iterates from 0 to the length of the List.
Inside the loop, compare the name if the ith element, and if it's equal to you search term, you've found it.
Something like this:
int index = -1;
for (int i = 0; i < pets.length; i++) {
if (pets.get(i).getName().equals(searchName)) {
index = i;
break;
}
}
// index now holds the found index, or -1 if not found
If you just want to find the object, you don't need the index:
pet found = null;
for (pet p : pets) {
if (p.getName().equals(searchName)) {
found = p;
break;
}
}
// found is now something or null if not found
As the others already stated, you cannot use indexOf() for this directly. It would be possible in certain situations (lambdas, rewriting hashCode/equals etc), but that is usually a bad idea because it would abuse another concept.
Here's a few examples of how we can do that in modern Java:
(as the index topic has already been answered quite well, this only handles direct Object return)
package stackoverflow.filterstuff;
import java.util.ArrayList;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.Predicate;
public class FilterStuff {
public static void main(final String[] args) {
final Pet dog = new Pet("Orio", 2); // again, naming conventions: variable names start with lowercase letters
final Pet cat = new Pet("Kathy", 4);
final Pet lion = new Pet("Usumba", 6);
final ArrayList<Pet> pets = new ArrayList<>();
pets.add(dog);
pets.add(cat);
pets.add(lion);
try {
simpleOldLoop(pets);
} catch (final Exception e) {
e.printStackTrace(System.out);
}
try {
simpleLoopWithLambda(pets);
} catch (final Exception e) {
e.printStackTrace(System.out);
}
try {
filterStreams(pets);
} catch (final Exception e) {
e.printStackTrace(System.out);
}
try {
filterStreamsWithLambda(pets);
} catch (final Exception e) {
e.printStackTrace(System.out);
}
}
private static void simpleOldLoop(final ArrayList<Pet> pPets) {
System.out.println("\nFilterStuff.simpleOldLoop()");
System.out.println("Pet named 'Kathy': " + filterPet_simpleOldLoop(pPets, "Kathy"));
System.out.println("Pet named 'Hans': " + filterPet_simpleOldLoop(pPets, "Hans"));
}
private static Pet filterPet_simpleOldLoop(final ArrayList<Pet> pPets, final String pName) {
if (pPets == null) return null;
for (final Pet pet : pPets) {
if (pet == null) continue;
if (Objects.equals(pet.getName(), pName)) return pet;
}
return null;
}
private static void simpleLoopWithLambda(final ArrayList<Pet> pPets) {
System.out.println("\nFilterStuff.simpleLoopWithLambda()");
System.out.println("Pet named 'Kathy': " + filterPet_simpleLoopWithLambda(pPets, (pet) -> Boolean.valueOf(Objects.equals(pet.getName(), "Kathy"))));
System.out.println("Pet named 'Hans': " + filterPet_simpleLoopWithLambda(pPets, (pet) -> Boolean.valueOf(Objects.equals(pet.getName(), "Hans"))));
}
private static Pet filterPet_simpleLoopWithLambda(final ArrayList<Pet> pPets, final Function<Pet, Boolean> pLambda) {
if (pPets == null) return null;
for (final Pet pet : pPets) {
if (pet == null) continue;
final Boolean result = pLambda.apply(pet);
if (result == Boolean.TRUE) return pet;
}
return null;
}
private static void filterStreams(final ArrayList<Pet> pPets) {
System.out.println("\nFilterStuff.filterStreams()");
System.out.println("Pet named 'Kathy': " + filterPet_filterStreams(pPets, "Kathy"));
System.out.println("Pet named 'Hans': " + filterPet_filterStreams(pPets, "Hans"));
}
private static Pet filterPet_filterStreams(final ArrayList<Pet> pPets, final String pName) {
return pPets.stream().filter(p -> Objects.equals(p.getName(), pName)).findAny().get();
}
private static void filterStreamsWithLambda(final ArrayList<Pet> pPets) {
System.out.println("\nFilterStuff.filterStreamsWithLambda()");
System.out.println("Pet named 'Kathy': " + filterPet_filterStreams(pPets, p -> Objects.equals(p.getName(), "Kathy")));
final Predicate<Pet> pdctHans = p -> Objects.equals(p.getName(), "Hans"); // we can also have 'lambda expressions' stored in variables
System.out.println("Pet named 'Hans': " + filterPet_filterStreams(pPets, pdctHans));
}
private static Pet filterPet_filterStreams(final ArrayList<Pet> pPets, final Predicate<Pet> pLambdaPredicate) {
return pPets.stream().filter(pLambdaPredicate).findAny().get();
}
}
Along with your Pet class, extended by toString():
package stackoverflow.filterstuff;
public class Pet { // please stick to naming conventions: classes start with uppercase letters!
private final String petName;
private final int petAge;
public Pet(final String name, final int age) {
petName = name;
petAge = age;
}
public String getName() {
return petName;
}
public int getAge() {
return petAge;
}
#Override public String toString() {
return "Pet [Name=" + petName + ", Age=" + petAge + "]";
}
}

Sorting of ArrayList<Track>

I want to sort ArrayList according to artist's name I have used comparator interface but I'm not able to sort the list. So kindly help me to solve the problem. The track data will be read from a file Trackdump. The file would contain one track data per line in the format TITLE/ARTIST/RATING/BPM
Here is the code:
import java.io.*;
import java.util.*;
public class MusicLibrary {
ArrayList<Track> songList = new ArrayList<Track>();
public static void main(String args[]) {
new MusicLibrary().go();
}
public void go() {
System.out.println("go");
getTracks();
System.out.println("Before Sorting:");
System.out.println(songList);
Collections.sort(songList);
System.out.println("Sorted according to Artist's name:");
System.out.println(songList);
}
void getTracks() {
System.out.println("gt");
File file = new File("TrackDump.txt");
try{
BufferedReader readr = new BufferedReader(new FileReader(file));
String line = null;
System.out.println(readr);
while ((line = readr.readLine()) != null) {
System.out.println(line);
addSong(line);
}
}catch(Exception e){
e.printStackTrace();
}
}
void addSong(String lineToParse) {
String[] tokens = lineToParse.split("/");
Track nextSong = new Track(tokens[0], tokens[1], tokens[2], tokens[3]);
songList.add(nextSong);
System.out.println(songList);
}
}
class Track implements Comparator<Track>
{
String title;
String artist;
String rating;
String bpm;
public int compare(Track o1, Track o2) {
return o1.getArtist().compareTo(o2.getArtist());
}
public Track(String a, String t, String r, String b) {
title = t;
artist = a;
rating = r;
bpm = b;
}
public boolean equals(Object aSong) {
return this.equals(aSong);
}
public String getArtist() {
return artist;
}
public String getBpm() {
return bpm;
}
public String getRating() {
return rating;
}
public String getTitle() {
return title;
}
public String toString() {
return title + "-" + artist;
}
}
Trackdump:
Title1/Artist1/8/320
Title2/Artist2/10/48
T5/A7/10/120
Title4/A7/9/240
T7/Artist5/7/320
Title6/Artist6/3/240
T9/A7/1/550
T6/Artist8/5/120
T1/Artist9/5/290
Song2/A0/5/320
Song5/A8/10/320
Song1/A2/6/290
You have to implement Comparable class to your Track class. Not Comparator. Then override compareTo() method. It would look like this:
public class Track implements Comparable<Track> {
// Variables, constructor, getters, setters ...
#Override
public int compareTo(Track other) {
return this.getArtist().compareTo(other.getArtist());
}
}
Finally sort with Collections.sort();
You need to implement the Comparable interface and then you can use Collections.sort().
class Track implements Comparable<Track> {
String title;
String artist;
String rating;
String bpm;
#Override
public int compare(Track other) {
return this.getArtist().compareTo(other.getArtist());
}
...
In theory it would work too when implementing Comparator but then you have to pass a Track object into Collections.sort() to act as the Comparator. But that is a rather weird way of doing it so better use the solution above.
Collections.sort(songList, new Track(null, null, null, null));

Actual and formal arguments differ in length

I have got the following code Simmulation.java, but when I tried compiling it, it is coming up with an error saying,
error: constructor CashewPallet in class CashewPallet cannot be applied to give types;
CashewPallet c1 = new CashewPallet();
Required: String,int, found: no arguments
Reason: Actual and formal arguments differ in length
I know what this error means, and when I tried to fix the line to CashewPallet c1 = new CashewPallet(String, int); and again CashewPallet c1 = new CashewPallet(nutType, id); but either didn't work! AND now I am not sure how can this be solved.
I am new to this, any help is much appreciated.
Many Thanks in advance!
Please bear with me.
EDIT : Thank you for the answers everyone! It has worked now and compiled successfully BUT when I executed it, it is coming up with error: ArrayIndexOutOfBoundsException :0 at Simmulation.main(Simmulation.java:201) Any help in fixing it Please?
THANK YOU!
This is Simmulation.java file
import java.io.File;
import java.util.LinkedList;
import java.util.Queue;
import java.util.*;
import java.util.Scanner;
import java.io.*;
public class Simmulation implements Operation {
Queue<CashewPallet> inputQueue=new LinkedList<CashewPallet>();
Stack<CashewPallet> stBay1=new Stack<CashewPallet>();
Stack<CashewPallet> stBay2=new Stack<CashewPallet>();
FileOutputStream fout4;
PrintWriter pw;
static int tick=0;
CashewPallet c1;
String temp;
Scanner sc;
public Simmulation(String fn)
{
int index=0;
String nutType="";
int id=0;
Scanner s2 ;
try
{
sc = new Scanner(new File(fn));
fout4=new FileOutputStream("nuts.txt");
pw=new PrintWriter(fout4,true);
String eol = System.getProperty("line.separator");
while(sc.hasNextLine())
{
tick++;
s2 = new Scanner(sc.nextLine());
if(s2.hasNext())
{
while ( s2.hasNext())
{
String s = s2.next();
if(index==0)
{
nutType=s;
}
else
{
id=Integer.parseInt(s);
}
index++;
}
System.out.println("Nuttype "+nutType+" Id is "+id+"tick "+tick);
if((nutType.equalsIgnoreCase("A")||nutType.equalsIgnoreCase("P")|| nutType.equalsIgnoreCase("C")|| nutType.equalsIgnoreCase("W")) && id!=0)
inputQueue.add(new CashewPallet(nutType.toUpperCase(),id));
System.out.println("Size of Queue "+inputQueue.size());
int k=0;
if(!inputQueue.isEmpty())
{
while(inputQueue.size()>k)
{
// stBay1.push(inputQueue.poll());
process(inputQueue.poll());
k++;
}
// System.out.println("Size of input "+inputQueue.size() +" Size of stay "+stBay1.size());
}
}
else
{
fout4.write(" ".getBytes());
}
index=0;
if(!stBay2.isEmpty())
{
while(!stBay2.isEmpty())
{
c1=stBay2.pop();
temp=tick+" "+c1.getNutType()+" "+c1.getId()+eol;
fout4.write(temp.getBytes());
}
// System.out.println("Nut final "+ stBay2.peek().getNutType());
}
else
{
temp=tick+eol;
fout4.write(temp.getBytes());
}
}
}
catch(Exception e)
{
System.out.println("Exception "+e);
}
closeStream();
}
public CashewPallet process( CashewPallet c)
{
//CashewPallet c=new CashewPallet();
int k=0;
//while(stBay.size()>k)
//{
//c=stBay.pop();
String operation=c.getNutType();
if(c.getPriority()==1)
{
shelling(c);
washing(c);
packing(c);
//stBay2.push(c);
}
else
{
switch(operation)
{
case "A": shelling(c);
washing(c);
packing(c);
break;
case "C": washing(c);
packing(c);
break;
case "W" : washing(c);
shelling(c);
packing(c);
break;
}
}
return c;
}
public void closeStream()
{
try
{
fout4.close();
}
catch(Exception e)
{
}
}
public boolean shelling(CashewPallet c)
{
// for(int i=0;i<20; i++)
{
System.out.println("Performing Shelling for "+c.getNutType());
}
return true;
}
public boolean washing(CashewPallet c)
{
// for(int i=0;i<20; i++)
{
System.out.println("Performing Washing for "+c.getNutType());
}
return true;
}
public boolean packing(CashewPallet c)
{
//for(int i=0;i<20; i++)
{
System.out.println("Performing Packing for "+c.getNutType());
}
stBay2.push(c);
return true;
}
public static void main(String args[])
{
new Simmulation(args[0]);
}
This is CashewPallet.java file
public class CashewPallet {
private String nutType;
private int id;
private int priority;
private int opTick;
public int getOpTick() {
return opTick;
}
public void setOpTick(int opTick) {
this.opTick = opTick;
}
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
this.priority = priority;
}
public CashewPallet(String nutType, int id) {
this.nutType = nutType;
this.id = id;
if(this.nutType.equalsIgnoreCase("p"))
{
priority=1;
}
else
{
priority=0;
}
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNutType() {
return nutType;
}
public void setNutType(String nutType) {
this.nutType = nutType;
}
When you use CashewPallet's constructor, you need to supply actual values for the arguments. The arguments are String nutType and int id, which means you need to supply a String that will go into nutType and an int that will go into id. For example:
CashewPallet c1 = new CashewPallet("Pecan", 42);
The constructor in CashewPallet requires a String and an int; you didn't provide them:
public CashewPallet(String nutType, int id)
You called it like this:
CashewPallet c1 = new CashewPallet();
Change it to something like:
CashewPallet c1 = new CashewPallet("Peanut",1337);
EDIT:
You're getting an ArrayIndexOutOfBoundsException on this line:
new Simmulation(args[0]);
That's in your args[0]. If that's out of bounds, then that means that you don't have command line arguments.
You should call it with command line arguments (or specifically one command line argument).
java Simmulation myarg
In this case your argument is the name of your file.

using 'this' keyword with extended classes in java

I have a class called 'Items' to which 'Equips' extends from and 'Helmet' then extends from 'Equips'. I have a method called 'getStats' that loads the item's stats from a .txt file. If I put the 'getStats' method in the 'Items' class, whatever field I try to access in a 'Helmet' object using 'this.' shows up null. The field I'm trying to access in 'Helmet' is initialized when the helmet is created before the text file is loaded. I could very easily just put the 'getStats' method in the 'Equips' class and put a blank 'getStats' method in the 'Items' class, but I was wondering if there was a way to make it work how it is. Thanks in advance!
Items.java:
package com.projects.aoa;
import static com.projects.aoa.Print.*;
import java.util.*;
import java.io.*;
class Items {
String name, type;
int id;
int hp, mp, str, def;
boolean vacent;
static void getAllStats(Items[] e){
for(Items i : e){
getItemStats(i);
}
}
static void getItemStats(Items i){
i.getStats();
}
void getStats(){
try {
//System.out.println(System.getProperty("user.dir"));
print(this.name); //THIS shows up as null as well as those \/below\/
FileInputStream fstream = new FileInputStream(System.getProperty("user.dir")
+ "/src/com/projects/aoa/" + this.type + this.name + ".txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;
int counter = 0;
while ((line = br.readLine()) != null) {
if (line.length() == 0){
break;
}
switch (counter) {
case 0:
this.hp = Integer.parseInt(line);
counter++;
break;
case 1:
this.mp = Integer.parseInt(line);
counter++;
break;
case 2:
this.def = Integer.parseInt(line);
counter++;
break;
case 3:
this.str = Integer.parseInt(line);
counter++;
break;
}
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Game.java:
Helmet headBand = new Helmet("HeadBand");
Helmet bronzeHelmet = new Helmet("BronzeHelmet");
Items[] equips = {
headBand, bronzeHelmet
};
getAllStats(equips);
Equips.java:
package com.projects.aoa;
import static com.projects.aoa.Print.print;
import static com.projects.aoa.Print.println;
import java.io.*;
class Equips extends Items{
String name, type;
int hp, mp, str, def;
void printStats(){
println("[" + name + "]");
println("Type: " + type);
println("HP: " + hp);
println("MP: " + mp);
println("Def: " + def);
println("Str: " + str);
}
}
class Helmet extends Equips {
Helmet(String name){
this.name = name;
this.type = "h_";
}
}
You haven't shown us your Helmet class, so it's hard to say what's going on - but my guess is that you're redeclaring fields with the same name in Helmet. Those will hide the fields in Items, whereas you really just want to use the fields from Items.
So here's a short but complete example which demonstrates what I think is going on:
class SuperClass {
String name;
public void setName(String newName) {
// This writes to the field in SuperClass
name = newName;
}
}
class SubClass extends SuperClass {
// This *hides* the field in SuperClass
String name;
public void showName() {
// This reads the field from SubClass, which
// nothing writes to...
System.out.println("My name is " + name);
}
}
public class Test {
public static void main(String[] args) {
SubClass x = new SubClass();
x.setName("Test");
x.showName();
}
}
I would recommend that:
You make all fields private, writing properties to give access to other classes as required
You get rid of the fields in Helmet which hide the ones in Items
You change your class names to avoid the plurality - Item and Equipment instead of Items
Here's a fixed version of the above code:
class SuperClass {
private String name;
public void setName(String newName) {
name = newName;
}
public String getName() {
return name;
}
}
class SubClass extends SuperClass {
public void showName() {
System.out.println("My name is " + getName());
}
}
public class Test {
public static void main(String[] args) {
SubClass x = new SubClass();
x.setName("Test");
x.showName();
}
}
(Obviously you also need to think about what access to put on the properties etc, but that's a separate matter.)

Categories

Resources