This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 5 years ago.
I'm making a DnD program to essentially just keep track of everything. I have three classes relevant to this problem, my main (which is just a hub to execute everything else), an Item class which holds all the properties of various individual items, and an InventoryList class which basically just defines an unholy load of items(this is a separate class because of the sheer number of items in 4e DnD). I had decided on making an Array of these Items, and calling that the users inventory; first off, is there a better way to do that -- i.e. using a HashMap or ArrayList? Second, I'm getting a classic "error, cannot find symbol" compiler error in the following code (shortened to relevance):
Main Method:
public class DnD {
public static void main (String[] args) throws FileNotFoundException, IOException {
. . .
Item[] myInventory = {Candle}; //error: symbol cannot be found
} //main()
} //DnD
Item Method:
public class Item {
. . .
public static Item Candle = new Item("Candle", 1, "Provides dim light for 2 squares, and lasts for 1 hour.");
public Item(String _name, double _price, String _desc) {
name = _name;
price = priceConverter(_price);
description = _desc;
} //Item()
} //Item
InventoryList Method:
public class InventoryList {
. . .
public InventoryList() {
// I have no idea where to proceed with this.
// Is there a way for me to use this to initialize ...
// ... an Array of Items in this method, to use in the main?
// The Item object stores name, price, and a description; ...
// ... is there a way to create an Array or similar to ...
// ... display all that information at once and hold it together?
}
}
I seem to be unable to summon Items in the main from the Item class. My Inventory (Item[]) is not working because of this.
For the "cannot find symbol" error, you can fix it like this:
Item[] myInventory = {Item.Candle};
Candle is defined in the class Item, so you have to type the class name out as well.
For how to implement InventoryList, I recommend using an ArrayList<Item> to store the player's items:
private ArrayList<Item> items = new ArrayList<>();
public ArrayList<Item> getItems() {
return items;
}
ArrayLists can dynamically change size, so if you want to add more items to the player's inventory, you can do that very conveniently.
You must qualify the static property
Item[] myInventory = {Item.Candle};
Second question is rather braod, do more research and ask a more focussed question.
Related
I realize that variations of this question have been asked before, but I am having a uniquely difficult time figuring out how to complete the following task:
I have an object that looks something like this (please note, "Skill" and "Certification" are ENUMS):
Public Employee {
String name;
List<Skill> employableSkills = new ArrayList<>();
List<Certification> certifications = new ArrayList<>();
...
}
In another class, I've got a
List<Employee> listOfEmployees;
and I'm trying to loop through it like this:
// determine the total number of employees who know Java
int numberOfEmployeesWhoKnowJava = 0;
for (Employee employee : listOfEmployees) {
if (employee.employableSkills.contains( ?? )) {
numberOfEmployeesWhoKnowJava++;
}
I'm struggling to get the exact syntax on the if-statement. I have tried this:
if(employee.employableSkills.contains(Employee.EmployableSkills.JAVA)) {
but EmployableSkills in this string gets "cannot resolve symbol."
How should I loop through the List on each Employee object and check if it contains JAVA?
Edit: It turns out I was making a fundamental error. In OOP, it is best not to expose the data from one class to another class. Instead, I wrote getters in the Employee class, then called those getters from my other class. That way, the data in Employee is not directly exposed to the class that needed it.
Even if you get syntax right, the following code will have a bad complexity of order n - O(n).
if(employee.employableSkills.contains(Employee.EmployableSkills.JAVA)) {
Change you List to hash implementation of set
Set<Skill> employableSkills = new HashSet<>();
and now loop through the employees
int numberOfEmployeesWhoKnowJava = 0;
for (Employee employee : listOfEmployees) {
if (employee.employableSkills.contains(Skill.JAVA)) {
numberOfEmployeesWhoKnowJava++;
}
}
This will give a complexity of O(1) while looking skills
Your question is a little unclear, but if my interpretation is correct, try this:
if (employee.employableSkills.contains(Skill.JAVA))
I would like to ask if there is a way to restrict a certain class to make more than a certain amount of instances. And if it is possible to make the compiler ("Eclipse") underline that line, when you try to make another instance (like it is an error in the code), or something along those lines?
Just to clarify for those who would say this is a bad idea, I am making a chess game, so I need it to not be able to make more than certain amount of playing pieces.
Eclipse can't do that at compile time, because it can't tell how many times a piece of code will be executed, and thus how many instances are created.
But you can design your class to only create a given number of instances, and make it impossibale to create more. For example:
public class Limited {
public static final List<Limited> ALL_INSTANCES =
Collections.unmodifiableList(createInstances());
private int id;
private static List<Limited> createInstances() {
List<Limited> result = new ArrayList<>();
for (int i = 0; i < 10; i++) {
result.add(new Limited(i));
}
}
private Limited(int id) {
this.id = id;
}
}
Since the constructor is private, the only 10 instances available are the ones in ALL_INSTANCES.
That said, that is not necessarily a good idea. Let's say you're creating a chess game. So by your logic, you shouldn't be able to create more than 2 King instances. What if your app handles 10 games at a time? Do you really want at most 2 Kings, or do you just want each ChessGame instance to have a black and a white King? Maybe all you need is something like
public class ChessGame {
private King blackKing = new King(BLACK);
private King whiteKing = new King(WHITE);
...
}
You can simply create the required number of objects - say by instantiating your class within a loop and then set a flag which is checked by the constructor so as to throw exception when an attempt is made to create one more. You can make the constructor private and have a static method to generate your instances.
Sorry, this might be duplicated, I'm not sure if my previous attempt to post this went through.
Started to learn Java several weeks ago, working on one of my first assignments. :)
My question is somewhat basic, but I couldn't find its exact equivalent after looking through previously resolved topics. This isn't a real life problem, so I guess it's expected from me to tackle it in a very specific way.
So the task consisted of several steps - I had to create a superclass with a number of custom objects, add new subclasses, implement new methods to count the value of certain variables, write test classes and sort my output.
It's all been done apart from this last step. Not sure if I'm allowed to just post my problems like that on the web, but here is where I am right now:
I have something like:
public class Pants
{
public enum SizeType {SMALL, MEDIUM, LARGE, EXTRA_LARGE}
private SizeType size;
private String brand;
private String countryOfOrigin;
private String color;
private double price;
//Other variables and methods
}
public class Jeans extends Pants
{
//new variables and methods
}
public class Shorts extends Pants
{
//some more new variables and methods
}
And other similar subclasses.
import java.util.ArrayList;
public class Selection
{
public static void main(String[] args){
Jeans ex1 = new Jeans("John Lewis");
ex1.countryOfOrigin("US");
ex1.color("Navy");
ex1.setSize(Pants.SizeType.LARGE);
ex1.setprice(40);
ex1.machineWashable(true);
System.out.println(ex1);
Shorts ex2 = new Shorts("Ted Baker");
ex2.countryOfOrigin("United Kingdom");
ex2.color("White");
ex2.setSize(Pants.SizeType.MEDIUM);
ex2.setprice(30);
ex2.machineWashable(true);
System.out.println(ex2);
//..etc
ArrayList<Pants> selection = new ArrayList<Pants>();
selection.add(ex1);
selection.add(ex2);
selection.add(ex3);
selection.add(ex4);
selection.add(ex5);
System.out.println( "Size - LARGE: " );
System.out.println();
Pants.SizeType size;
size = Pants.SizeType.LARGE;
ListPants(selection,size);
I need to write a ListPants method to list objects depending on SizeType - starting with large in this case. I don't think I can implement any additional interfaces (which is what was mostly recommended in other threads).
Please see my attempt below (didn't work). Am I thinking in the right direction here, or?
public static void ListPants(ArrayList<Pants> selection, Pants.SizeType size)
{
for (Pants.SizeType sizeType : Pants.SizeType.values()) {
for (Pants pants : selection) {
if (pants.getSize().equals(sizeType)) {
System.out.println(selection.toString());
I think it's just a minor problem you're facing. You already defined the signature of the method which should print out all pants of a specific size:
ListPants(ArrayList<Pants> selection, Pants.SizeType size)
That is correct. Now, your code is looping over all pants and over all possible sizes:
public static void ListPants(ArrayList<Pants> selection, Pants.SizeType size)
{
for (Pants.SizeType sizeType : Pants.SizeType.values()) {
for (Pants pants : selection) {
if (pants.getSize().equals(sizeType)) {
System.out.println(selection.toString());
Since this looks like a homework assignment, i'll phrase my answer as a question:
Where are you using the size parameter in the method body of ListPants?
I am assuming your class cannot implement new interfaces, and not using interfaces at all.
You can use Collections.sort(List,Comparator) with a Comparator, which is built for your class.
Something like
Collections.sort(selection,new Comparator<Pants>() {
#Override
public int compare(Pants p1, Pants p2) {
//implement your compare method in here
...
}
});
If you are eager to create your own sorting algorithm, have a look of this list of sorting algorithms. Simplest to implement (though pretty slow) IMO is selection-sort
I'm new to Java and I'm currently writing a program for an assignment that represents a 'sports league' (classes to represent player/club/match/league)
My main problems are occurring in the league class. Here are the relevant variables to give you an idea how I'm storing things:
public class League
{
private String leagueName;
private ArrayList<Club> clubs;
private ArrayList<Match> fixtures;
private ArrayList<String> results2;
private TreeMap<Match, String> results;
private String topTeam;
private String goldenBoot;
}
Currently trying to write a method in the League class which will print a 'league table' - i.e. a list of Clubs sorted by their points tally (held as variable in Club class) and I'm drawing a blank on it.
Further to this, I need to write two methods to find the top scorer (golden boot) and find the top team in the league; again I am drawing a blank. Perhaps I am overcomplicating things?
Would be very grateful for suggestions/sample methods
EDIT:
Ok, so that method I'm trying to write is something beginning with:
public void getLeagueTable() {
for(Club c : clubs) {
c.getTally();
}
}
which would give the tally value for each Club object - but how to sort these results, and how to associate the highest with one Club is what's really troubling.
To print the league table, you are going to need to sort the club array and then loop through each item and print the club name.
To sort the club array try using Collections.sort http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Collections.html
.. that is assuming you havent been told to implement your own algorithm
Again, more sorting required to get the top team and top scorer, then you will need to pick the top item from the sorted list.
Hope that helps...
You better use Set rather than ArrayList. And here is a good start for your question :
void printLeagueTable(){
i = 0 ;
while( i != clubs.size() ){
Club club = clubs.get(i);
System.out.println("club: "+i+ "points: " club.points() );
}
}
I have used linked lists before with Strings, doubles, etc., and they always worked exactly as expected. But now I am forming a linked list of items, and whenever I add a new element to the list, all objects in the list apparently become equal to the last object.
The essential code is as below:
import java.util.*;
public class Global
{
static public LinkedList<StockInfo> DiaryStocks = new LinkedList<StockInfo>();
static public class StockInfo //info related to each stock in diary
{
String recordDate;
String ticker;
int status;
String buyDate;
String sellDate;
double buyPrice;
double sellPrice;
double nmbrShares;
}//StockInfo
//The following function places the Diary data for a stock in the arraylist
static public void AddDiaryData(StockInfo thisdata)
{
String tckr;
int i;
DiaryStocks.add(thisdata);
for (i = 0; i < DiaryStocks.size(); i++) //this is debug code
{
tckr = DiaryStocks.get(i).ticker;
}
}
}
As I said, when single stepping through the debug code near the bottom, each time I add a new item to the list, the list size grows as it should, but the tckr item only corresponds to the last item added.
Any insights into this puzzle would be greatly appreciated.
John Doner
The problem is outside the code your provide. It is most likely that you are adding the same instance of StockInfo. Perhaps you have something like:
StockInfo info = new StockInfo();
for (...) {
info.setFoo(..);
info.setBar(..);
AddDiaryData(info);
}
You should not reuse instances like that. You should create a new instance each time.
As a sidenote - method names in Java should start with lowercase letter.
From the symptoms you are describing, it seems as if you are always adding a reference to the same StockInfo object instance to your list, rather than a reference to a new copy each time.
When that object is updated with the contents of the new entry, all list entries appear to change to reflect that latest entry.
This problem lies outside the code snippet that you posted, perhaps in the caller of the AddDiaryData method.
Ooops.
Deep Copy please search it
DiaryStocks.add(thisdata);
you should create new StockInfo() then add to the list otherwise you add the reference and it equalize all the reference of items to the last one