Use while loops to read file - java

I'm working on a project for school and I'm having some trouble here. I am to go through a file for a trivia game. The format of the file is as follows: The first line of the file will be the category of the questions, the following lines will be pairs of questions and answers. Until it hits a blank line, that indicates that the next line after the blank line starts a new category and it goes on. I am supposed to make an ArrayList that will have 6 indexes. One for each category, then in each of the indexes i should have groups of questions and answers that I will be able to utilize for comparison. I guess essentially an array inside of an arraylist.
I hope that what im trying to accomplish makes sense. Its very confusing to me. But here is the code of what Im trying to work on and with so many parts im getting very messed up.
import java.util.ArrayList;
public class TriviaQuestion {
private String player;
private String category;
private String question;
private String answer;
private int score = 0;
/**
*
*/
public TriviaQuestion() {
player = "unknown";
category = "unknown";
question = "unknown";
answer = "unknown";
score = 0;
}
public TriviaQuestion(String category, String question, String answer){
}
public TriviaQuestion(String question, String answer){
}
public TriviaQuestion(String player, String category, String question,
String answer, int score) {
super();
this.player = player;
this.category = category;
this.question = question;
this.answer = answer;
this.score = score;
}
/**
* #return the player
*/
public String getPlayer() {
return player;
}
/**
* #param player the player to set
*/
public void setPlayer(String player) {
this.player = player;
}
/**
* #return the category
*/
public String getCategory() {
return category;
}
/**
* #param category the category to set
*/
public void setCategory(String category) {
this.category = category;
}
/**
* #return the question
*/
public String getQuestion() {
return question;
}
/**
* #param question the question to set
*/
public void setQuestion(String question) {
this.question = question;
}
/**
* #return the answer
*/
public String getAnswer() {
return answer;
}
/**
* #param answer the answer to set
*/
public void setAnswer(String answer) {
this.answer = answer;
}
/**
* #return the score
*/
public int getScore() {
return score;
}
/**
* #param score the score to set
*/
public void setScore(int score) {
this.score = score;
}
/* (non-Javadoc)
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
return "TriviaQuestion [category=" + category + ", question="
+ question + ", answer=" + answer + "]";
}
}
Then the tester, I tried to take some notes about it at the bottom in class, but they don't make a lot of sense to me at this point.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class TriviaQuestion2 {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
File gameFile = new File("trivia.txt");
Scanner inFile = new Scanner(gameFile);
ArrayList<TriviaQuestion> question = new ArrayList<TriviaQuestion> ();
while (inFile.hasNextLine()){
boolean cat = inFile.hasNextLine();
boolean more = true;
while (inFile.hasNextLine() && more);
String answer;
TriviaQuestion temp = new TriviaQuestion(question, answer);
question[0] = new ArrayList<TriviaQuestion>();
new TriviaQuestion(q,a);
question[0].add(temp);
}
}
}
inFile.close();
//use a while loop inside a while loop, and first do category, then question/answer
//there are six categories, use array of trivia questions ArrayList <triviaquestions>[]
//question = new ArrayList<triviaQuesitons>[6]
//question[0] = new ArrayList<triviaQuesitons>();
/**
* while in question[0] and so on read the quesiton and answer
* temp = new tq(question, answer)
* question [0].add(temp)
* question[0].get(i)
*
*/
System.out.println(question);
}
// TODO Auto-generated method stub
}

You want some nested loops to read the file.
That's a poor way to describe the file-format. "Section" describes a section of the file. You can say that each section defines a category, with the first line the name of the category, subequent lines pairs of questions and answers, and terminated by a blank line/ or EOF.
In pseudocode, essentially you want:
List<Category> categories = new ArrayList();
while (in.hasNextLine()) {
String catName = in.readLine();
if (catName.trim().length() == 0)
continue; // skip extra blank lines between Sections.
Category cat = new Category( catName);
categories.add( cat);
while (in.hasNextLine()) {
String line = in.readLine();
if (line.trim().length() == 0)
break; // end of Section.
// parse a Question & it's Answer.
TriviaQuestion question = parseQuestion( line);
cat.addQuestion( question);
}
}
// done.
return categories;
I am supposed to make an ArrayList that will have 6 indexes. One for
each category, then in each of the indexes i should have groups of
questions and answers that I will be able to utilize for comparison.
That's a fairly confused way of talking about something that actually should be pretty simple. You could say "there will be 6 categories". But actually, it's not necessary to fix or predetermine the size of the ArrayList -- so why mumble about this at all?
I guess essentially an array inside of an arraylist.
Use an ArrayList (indirectly) inside of an ArrayList. Lists/ArrayLists are much better to build dynamically, because (unlike an array) they don't have to be pre-sized or grown.
But note that the 'Questions' list, should be held inside of the Category obect.

Related

How do I access a private member from a subclass

Trying to print the username in the method printShortSummary in the MessagePost class. The username is private in the Post class. Doing this for educational purposes. Still getting error that the username is private in Post.
import java.util.ArrayList;
/**
* This class stores information about a news feed post in a
* social network. Posts can be stored and displayed. This class
* serves as a superclass for more specific post types.
*
* #author Michael Kölling and David J. Barnes
* #version 0.2
*/
public class Post
{
private String username; // username of the post's author
private long timestamp;
private int likes;
private ArrayList<String> comments;
/**
* Constructor for objects of class Post.
*
* #param author The username of the author of this post.
*/
public Post(String author)
{
username = author;
timestamp = System.currentTimeMillis();
likes = 0;
comments = new ArrayList<>();
}
public void getUserName()
{
getUserName();
}
/**
* Record one more 'Like' indication from a user.
*/
public void like()
{
likes++;
}
/**
* Record that a user has withdrawn his/her 'Like' vote.
*/
public void unlike()
{
if (likes > 0) {
likes--;
}
}
/**
* Add a comment to this post.
*
* #param text The new comment to add.
*/
public void addComment(String text)
{
comments.add(text);
}
/**
* Return the time of creation of this post.
*
* #return The post's creation time, as a system time value.
*/
public long getTimeStamp()
{
return timestamp;
}
/**
* Display the details of this post.
*
* (Currently: Print to the text terminal. This is simulating display
* in a web browser for now.)
*/
public void display()
{
System.out.println(username);
System.out.print(timeString(timestamp));
if(likes > 0) {
System.out.println(" - " + likes + " people like this.");
}
else {
System.out.println();
}
if(comments.isEmpty()) {
System.out.println(" No comments.");
}
else {
System.out.println(" " + comments.size() + " comment(s). Click here to view.");
}
}
/**
* Create a string describing a time point in the past in terms
* relative to current time, such as "30 seconds ago" or "7 minutes ago".
* Currently, only seconds and minutes are used for the string.
*
* #param time The time value to convert (in system milliseconds)
* #return A relative time string for the given time
*/
private String timeString(long time)
{
long current = System.currentTimeMillis();
long pastMillis = current - time; // time passed in milliseconds
long seconds = pastMillis/1000;
long minutes = seconds/60;
if(minutes > 0) {
return minutes + " minutes ago";
}
else {
return seconds + " seconds ago";
}
}
}
import java.util.ArrayList;
/**
* This class stores information about a post in a social network news feed.
* The main part of the post consists of a (possibly multi-line)
* text message. Other data, such as author and time, are also stored.
*
* #author Michael Kölling and David J. Barnes
* #version 0.2
*/
public class MessagePost extends Post
{
private String message; // an arbitrarily long, multi-line message
/**
* Constructor for objects of class MessagePost.
*
* #param author The username of the author of this post.
* #param text The text of this post.
*/
public MessagePost(String author, String text)
{
super(author);
message = text;
}
public static void printShortSummary()
{
Post.getUserName();
System.out.print ("Message postfrom" + username);
}
/**
* Return the text of this post.
*
* #return The post's message text.
*/
public String getText()
{
return message;
}
}
You should be calling getUserName() but obviously cannot because it returns void and causes a Stack Overflow exception if called:
public void getUserName()
{
getUserName();
}
This should be
public String getUserName()
{
return userName;
}
And then that's how you access the user name from the subclass.
After that you would modify this method to be:
public static void printShortSummary()
{
//Post.getUserName();
System.out.print ("Message postfrom" + getUserName());
}
The portion where you have Post.getUserName(); doesn't make any sense, it's not a static method and can't be referenced in that manner.
If you don't have access to Post class or you don't wanna change Post class, you can use java Reflection API to access private members in any class
Ex:
public void printShortSummary() throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
Field field = Post.class.getDeclaredField("username");
field.setAccessible(true);
System.out.print("Message post from " + field.get(this).toString());
}
Note : Anyway this not the object oriented way

Taking a CSV file, splitting it, and adding each split part into an attribute of an object

I am at a sticking point with an assignment I have been working on. It is a program that creates a Periodic Table of the Elements. To create each element, I need to take a file(a CSV), split it, and set each split part as an attribute of an object called "Element". Splitting each line of the file and reading it in has so far been no problem. However, I have been stuck on how to take each part and add it as the attribute of the Element object. Can anyone please shed some light on this?
Here is my code:
"Periodic Table" class:
public class PeriodicTable {
private String line;
private String[] parts;
private String filename = "file.csv";
public PeriodicTable() throws IOException {
}
public void readValues(String filename) throws IOException{
Scanner sc = new Scanner(new FileReader(filename));
ArrayList<Element> ar1 = new ArrayList<Element>();
while(sc.hasNextLine()){
line = sc.nextLine();
parts = line.split(",");
Element el = new Element();
el.setChemicalName(parts[0]);
el.setAtomNum(parts[1]);
el.setMeltPoint(parts[3]);
el.setBoilPoint(parts[4]);
el.setDensity(parts[5]);
el.setAtomWeight(parts[6]);
// System.out.println(el.getChemicalName());
//System.out.println(el.getAtomWeight());
ar1.add(el);
}
System.out.println(ar1);
}
}
The "Element" class
public class Element {
private String chemicalName;
private String atomNum;
private String boilPoint;
private String meltPoint;
private String density;
private String atomWeight;
public Element() throws IOException{
}
/**
* #return the chemicalName
*/
public String getChemicalName() {
return chemicalName;
}
/**
* #param chemicalName the chemicalName to set
*/
public void setChemicalName(String chemicalName) {
this.chemicalName = chemicalName;
}
/**
* #return the atomNum
*/
public String getAtomNum() {
return atomNum;
}
/**
* #param atomNum the atomNum to set
*/
public void setAtomNum(String atomNum) {
this.atomNum = atomNum;
}
/**
* #return the boilPoint
*/
public String getBoilPoint() {
return boilPoint;
}
/**
* #param parts2 the boilPoint to set
*/
public void setBoilPoint(String parts2) {
this.boilPoint = parts2;
}
/**
* #return the meltPoint
*/
public String getMeltPoint() {
return meltPoint;
}
/**
* #param parts2 the meltPoint to set
*/
public void setMeltPoint(String parts2) {
this.meltPoint = parts2;
}
/**
* #return the density
*/
public String getDensity() {
return density;
}
/**
* #param density the density to set
*/
public void setDensity(String density) {
this.density = density;
}
/**
* #return the atomWeight
*/
public String getAtomWeight() {
return atomWeight;
}
/**
* #param input the atomWeight to set
*/
public void setAtomWeight(String input) {
this.atomWeight = input;
}
#Override
public String toString(){
return chemicalName;
}
}
Because the String.split() method uses an array to hold each part that is split, I tried to set the values to each attribute using a reference to the index in the parts array that holds the value, for example....
el.setChemicalName(parts[0]));
However, this doesn't seem to be working - when I try to print out the value of that variable, I usually get a null value.
I recommend you to use OpenCSV to make your life easier.
Your code work fine, but please
Check the variable filename , maybe you pass an wrong value when call the method readValues.
Are you sure the token separator of your CSV file is a comma ",". If you're using an office application (Excel in MS Office or Calc in Libre/Open Office) if you don't especify the token the default separator is a semicolon ";".
In method String.split it's better use parts = line.split("\\,"); because split use and regular expressions to make the separation in String array.

Condition to check if a value exists in list containing objects,

I am trying to write an if condition to check a value exists in a list containing many objects,
Here is my code:
List<TeacherInfo> teacherInfo=ServiceManager.getHelperService(TeacherManagementHelper.class, request, response).getTeacherInfoId();
if(teacherInfo.contains(inputParam))
{
out2.println("<font color=red>");
out2.println("Id Not Available");
out2.println("</font>");
}
else
{
out2.println("<font color=green>");
out2.println("Id Available");
out2.println("</font>");
}
after executing 1st sentence getTeacherInfoId() method successfully returns a list of objects, in those objects I want to check any object has a value same as inputParam. Is my above code right ? if wrong please help me .
contains(Object o) is internally based on equals between objects of your list and your input, as stated by the doc.
Since you said that inputParam is an integer, then the current state of your code can't work because you compare an integer to TeacherInfo objects, so they won't ever be equal. I believe you want to compare inputParam to one particular field of TeacherInfo objects.
If you're using Java 8, you can use the stream API instead of contains():
List<TeacherInfo> teacherInfo=ServiceManager.getHelperService(TeacherManagementHelper.class, request, response).getTeacherInfoId();
if (teacherInfo.stream().anyMatch(ti -> ti.getId() == inputParam)) {
// contains the id
} else {
// does not contain the id
}
For previous java versions, an alternative to contains() would be to iterate over your list and compare manually your integer to the TeacherInfo's field:
private static boolean containsTeacherId(List<TeacherInfo> teacherInfos, int id) {
for (TeacherInfo ti : teacherInfos) {
if (ti.getId() == inputParam) { // I used getId(), replace that by the accessor you actually need
return true;
}
}
return false;
}
Then:
List<TeacherInfo> teacherInfo=ServiceManager.getHelperService(TeacherManagementHelper.class, request, response).getTeacherInfoId();
if (containsTeacherId(teacherInfo, inputParam)) {
// contains the id
} else {
// does not contain the id
}
Note: If you don't need other information than the ID itself, I'd rather suggest to return the list of IDs from a method called getTeacherIds(), especially if this information comes from a DB.
No it won't work at all. you should iterate the 'teacherInfo' list and you need to override the compare()and hashvalue() of object class.
You would need to iterate over the list teacherInfo and compare each element of that list with inputParam.
Below is a small demo code that might help you.
I have created a testerInfo analogous to your teacherInfo and param analogous to your inputParam.
I hope it helps.
Tester.java
/**
*
*/
package com.demo;
/**
* #author Parul
*
*/
public class Tester {
private int id;
private String name;
/**
* #return the id
*/
public int getId() {
return id;
}
/**
* #param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
public Tester(int id, String name) {
this.id = id;
this.name = name;
}
public Tester() {
}
}
Demo.java
/**
*
*/
package com.demo;
import java.util.ArrayList;
import java.util.List;
/**
* #author Parul
*
*/
public class Demo {
public static void main(String [] args){
List<Tester> testerInfo=new ArrayList<Tester>();
testerInfo.add(new Tester(1,"Java"));
testerInfo.add(new Tester(2,"C++"));
testerInfo.add(new Tester(3,"Python"));
testerInfo.add(new Tester(4,"C"));
Tester tester=null;
int param=2;
for(int i=0;i<testerInfo.size();i++){
tester=testerInfo.get(i);
if(tester.getId()==param){
System.out.println("param found: "+tester.getName());
break;
}
}
}
}
OUTPUT
param found: C++

Cannot make static reference to non-static object

This is my first Java project.
So I'm working on my own simulation project, and some of my core stuff has gone awry. I have two classes I'm focusing on right now - settlement and townRey, which extends settlement.
The error is thrown when I try
System.out.println(townRey.returnStrength());
Here are my two relevant classes:
settlement:
public class settlement
{
//
//
// VARIABLES
//
//
/**
* The town's unique name.
*/
public String name;
/**
* The settlement's location in latitude (N-S)
*/
public int latitude;
/**
* The settlement's location in longitude (E-W)
*/
public int longitude;
/**
* What faction a town or village is aligned to. This determines production and consumption, mostly.
*/
public String faction;
/**
* What a specific village or town produces.
*/
public String[] production;
/**
* What a specific town consumes (villages don't consume)
*/
public String[] consumption;
/**
* How dangerous a specific town is with bandits
* A 1-10 scale, with 10 being the most dangerous.
* Any town with a danger over 8 can be raided and destroyed temporarily by bandits.
* Being raided successfully depends on the Strength of a town.
*/
public int danger;
/**
* How much a town takes in taxes.
*/
public float tax;
/**
* How easily a town is raided by bandits.
* If a bandit raid has a lower strength than the town, then the town wins.
*/
public int strength;
//
//
// METHODS
//
//
public int returnLatitude()
{
return latitude;
}
public int returnLongitude()
{
return longitude;
}
public String returnFaction()
{
return faction;
}
public String[] returnProduction()
{
return production;
}
public String[] returnConsumption()
{
return consumption;
}
public int returnDanger()
{
return danger;
}
public float returnTax()
{
return tax;
}
public int returnStrength()
{
return strength;
}
}
and townRey:
public class townRey extends settlement
{{
name = "Rey";
latitude = 5;
longitude = 5;
String faction = "Nord";
String[] production;
String[] consumption;
danger = 1;
tax = 0.05F;
strength = 6;
}}
EDIT:: Thanks for all the help! I fixed all issues now. Below is 'Settlement' and 'Start'.
public class Settlement
{
//
//
// VARIABLES
//
//
/**
* The town's unique name.
*/
public String name;
/**
* The settlement's location in latitude (N-S)
*/
public int latitude;
/**
* The settlement's location in longitude (E-W)
*/
public int longitude;
/**
* What faction a town or village is aligned to. This determines production and consumption, mostly.
*/
public String faction;
/**
* What a specific village or town produces.
*/
public String[] production;
/**
* What a specific town consumes (villages don't consume)
*/
public String[] consumption;
/**
* How dangerous a specific town is with bandits
* A 1-10 scale, with 10 being the most dangerous.
* Any town with a danger over 8 can be raided and destroyed temporarily by bandits.
* Being raided successfully depends on the Strength of a town.
*/
public int danger;
/**
* How much a town takes in taxes.
*/
public float tax;
/**
* How easily a town is raided by bandits.
* If a bandit raid has a lower strength than the town, then the town wins.
*/
public int strength;
//
//
// METHODS
//
//
public int returnLatitude()
{
return latitude;
}
public int returnLongitude()
{
return longitude;
}
public String returnFaction()
{
return faction;
}
public String[] returnProduction()
{
return production;
}
public String[] returnConsumption()
{
return consumption;
}
public int returnDanger()
{
return danger;
}
public float returnTax()
{
return tax;
}
public int returnStrength()
{
return strength;
}
}
and Start, where I create 'townRey' then access a bit of data in two different ways.
public class Start
{
public static void main(String[] args)
{
//Creates 'Rey'
Settlement townRey = new Settlement();
townRey.name = "Rey";
townRey.latitude = 5;
townRey.longitude = 5;
townRey.faction = "Nord";
townRey.danger = 1;
townRey.tax = 0.05F;
townRey.strength = 6;
//This calls the returnLongitude method from Settlement, and is the 'proper' way to do it.
System.out.println(townRey.returnLongitude());
//This also works.
System.out.println(townRey.longitude);
//Thanks for the help!
}
}
townRey shouldn't be extending settlement. You should be declaring it as an instance of settlement in some method, as follows:
townRey = new settlement();
townRey.name = "Rey";
...
townRey.strength = 6;
Or, better still, making a new constructor for settlement that takes the different fields as inputs.
Also, a style note: Generally, in Java, classes should begin with a capital letter, so Settlement rather than settlement might make a better name.
You should define a townRey object then use this object to call returnStrength
townRey mytownRey = new townRey();
System.out.println(townRey.returnStrength());
I expect you want townRey to be an instance of settlement, not a subclass. Unless you want to have multiple copies of townRey. Replace the line public class townRey extends settlement with settlement townRey = new settlement(), and add a semicolon after }}. Leave everything else the same.
public class mainclss()
{
public static void main(String arg[])
{
townRey= new settlement();
//you can do sth you like
}
}
create a new class to check.DO NOT start Java with Class!It is a little difficult.
Create a separate class with main() method. Inside this method, you should create an object of townRey, in order to access the method returnStrength(). You can't access it using the class name 'townRay' if you are doing so. So Add this class with the code below:
public class MainClass {
public static void main(String[] args) {
townRey tr = new townRey();
System.out.println( tr.returnStrength () );
}
}
This worked fine with me. So you can safely use it.
NOTE: You should learn by practice to start each word in your class name with a capital letter such as Settlement and TownRey. Good Luck!

Java Object Array Foreach Method Access

After developing in PHP for a long time I have decided to step into Java. Comfortable in OOP methodology and all that, I'm trying to start off at that point within java, but I'm getting hung up on passing out my arraylist object into a for statement to be printed back out using the Item class methods.
HelloInvetory.java
package helloInventory;
import java.util.Arrays;
public class HelloInventory {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Object InvetoryItems;
Inventory inv = new Inventory();
inv.createItemObj(101, "camera", "Used camera that I bought off of a homeless guy.", 500);
InvetoryItems = inv.getAllInventoryItems();
for(Object item : InvetoryItems){
System.out.println(item.getItemName());
}
System.out.println("Done");
}
}
Inventory.java
package helloInventory;
import java.util.*;
/**
* Tracks and maintains all items within the inventory
* #author levi
*
*/
public class Inventory {
List<Object> InventoryItems = new ArrayList<Object>();
/*
* create object from Items class
* and insert into Object[] array.
*/
public void createItemObj(int sku, String name, String descriptor, float price) {
Items item = new Items();
item.setSku(sku);
item.setItemName(name);
item.setItemDescription(descriptor);
item.setItemPrice(price);
this.setInventoryItems(item);
}
public Object getAllInventoryItems() {
//return InventoryItems;
return this.InventoryItems.toArray();
}
public void setInventoryItems(Object inventoryItems) {
//InventoryItems.add(inventoryItems);
this.InventoryItems.add(inventoryItems);
}
}
Items.java
package helloInventory;
/**
* Class object to hold each item details
* #author levi
*
*/
public class Items {
int sku;
String itemName;
String itemDescription;
float itemPrice;
public int getSku() {
return sku;
}
public void setSku(int sku) {
this.sku = sku;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getItemDescription() {
return itemDescription;
}
public void setItemDescription(String itemDescription) {
this.itemDescription = itemDescription;
}
public float getItemPrice() {
return itemPrice;
}
public void setItemPrice(float itemPrice) {
this.itemPrice = itemPrice;
}
}
Where I am stuck is within the HelloInventory.java
for(Object item : InvetoryItems){
System.out.println(item.getItemName());
}
IDE (Eclipse) gives me the error "Can only iterate over an array or an instance of java.lang.Iterable". Is there something extra I need, or I'm I going around this totally the wrong way in Java? Correct example would be helpful.
Best,
Levi
You have a very strange architecture here my friend. You shouldn't be using generic Objects everywhere, but the actual types. First thing:
public Object getAllInventoryItems() {
//return InventoryItems;
return this.InventoryItems.toArray();
}
Why not just return the List itself?
public List<Item> getAllInventoryItems() {
return this.InventoryItems;
}
Also change this:
List<Item> InventoryItems = new ArrayList<Item>();
and this:
public void setInventoryItems(Item inventoryItems) {
this.InventoryItems.add(inventoryItems);
}
Now iterating the List is smooth sailing:
public static void main(String[] args) {
// TODO Auto-generated method stub
List<Item> InvetoryItems;
Inventory inv = new Inventory();
inv.createItemObj(101, "camera", "Used camera that I bought off of a homeless guy.", 500);
InvetoryItems = inv.getAllInventoryItems();
for(Item item : InvetoryItems){
System.out.println(item.getItemName());
}
System.out.println("Done");
}
Btw, I changed Items to Item out of habit. A class name should indicate a single entity so by convention it's singular.
Now don't take this the wrong way, but you may have got off on the wrong foot with Java, so I highly recommend this reading: http://www.mindview.net/Books/TIJ/ This worked for me when I was starting with Java, maybe others can suggest some good sources as well.
Ok, two things. One is that Tudor is absolutely right, it's best to use the classes you're expecting directly, not Objects, and stylistically his points are accurate too.
Two is that if you really have to use a list of object, you'll need to cast back from object to whatever type it is that you're expecting to receive.
List<Object> list = inv.getAllInventoryItems();
for (Object item : list){
System.out.println((Items) item).getItemName();
}
However, I wouldn't recommend doing this as it effectively takes what should be a compile-time error and makes it a RunTime error (if the class cannot be cast).

Categories