this is my first question on here and I did a search before forming it, so I hope everything is as required.
I am working on a school assignment in Java. I am able to produce the required output but there are a lot of null instances created first. I don't understand why. Information about the library the professor created for the course and the code are below
Library included with this course: i2c.jar. It can be found here.
included in this Library are the classes Country and CountryDB. The API for the Country class can be found at http://130.63.94.24/~roumani/book/doc/i2c/ca/roumani/i2c/Country.html
The API for the CountryDB class can be found at http://130.63.94.24/~roumani/book/doc/i2c/ca/roumani/i2c/CountryDB.html
I am asked to create a class called Game, using the Country and CountryDB APIs.
The only attribute is db, which is an instance of CountryDB.
The constructor only sets the attribute (db) for this instance to a new CountryDB object.
The class is also meant to include a method (called qa) that follows this pseudocode:
get a reference to the database's capital city list
determine the size of this list. Cal it n.
generate a random number in [0,n) called index.
invoke get(index) on the list to get a random capital city. Call it c
get a reference to the database's data map
invoke get(c) on the map to get a reference to a country. Call it ref.
The method is then supposed to return one of two Strings (which will be clear in the code). Everything works as it should, except I get a lot of "nulls" before the desired output. When made into a List, db has size 241 so I suspect I am creating 241 null instances and 1 proper instance. I have no idea why though. I have tested every line of code in my method and the constructor was dictated by the textbook.
CODE
package ca.yorku.eecs.caps;
import java.util.List;
import java.util.Map;
import ca.roumani.i2c.Country;
import ca.roumani.i2c.CountryDB;
public class Game
{
private CountryDB db;
public Game()
{
this.db = new CountryDB();
}
public String qa()
{
List<String> capitals = db.getCapitals();
System.out.println(capitals.toString());
int n = capitals.size();
System.out.println(n);
int index = ((int) (n * Math.random()));
System.out.println(index);
String c = capitals.get(index);
System.out.println(c);
Map<String, Country> data = db.getData();
Country ref = data.get(c);
if (Math.random() > 0.5)
{
return "What is the capital of " + ref.getName() + "? \n" + ref.getCapital();
}
else
{
return ref.getCapital() + " is the capital of? \n" + ref.getName();
}
}
public static void main(String[] args)
{
Game g = new Game();
System.out.println(g.qa());
}
}
the System.out.println() statements are only there to test when the nulls occur. It clearly happens immediately because my psvm output is 241 nulls (on separate lines) followed by my desired output. Can somebody please tell me what I am doing wrong?
And, more generally (to help more people) how do you implement classes, the constructor of which instantiates another class and sets it as an attribute value?
I appreciate any help. Also, please note, I am not trying to get others to do my work for me. I've spent hours on this and my lab TA also wasn't sure why it happens either. He would have helped me correct it had he known how.
Thank you.
I've done most part of this. Anyone give me a small hint about how do I find the number of 10s in the list.
Eg. Input would be
[10,4,6,10,6,7]
Output must be
[4,6,6,7,0,0]
import java.util.ArrayList;
import java.util.List;
public class prob64 {
public static List output;
public static void getVal(List ll)
{
int count=0;
List ll1=new ArrayList();
for(int i=0;i<ll.size();i++)
{
if((int)ll.get(i)!=10)
{
ll1.add(ll.get(i));
}
if((int)ll.get(i)==10)
{
count++;
}
}
if(count>0)
{
ll1.add(8);
}
output=ll1;
System.out.println(output);
}
public static void main(String[] args) {
List<Integer> ll=new ArrayList();
ll.add(10);
ll.add(1);
ll.add(10);
ll.add(2);
prob64.getVal(ll);
}
}
The current output I'm getting is [1,2,0]. I'm supposed to get [1,2,0,0]
List.remove(Object) removes the first matching element. It also returns a boolean indicating if a removal was really done, so this should work :
while(ll.remove(10)) {
ll.add(0);
}
That is, as long as you find 10s to remove, add 0s. Note that List.add adds the element at the end of the list, which is your requirement (if I'm correct).
I suppose this is some kind of learning exercise, but I would advise you to find better names for your variable (ll & ll1 does not make your function easy to read).
You are adding only one zero at the end of the loop (in case 10s were found). You should count the number of 10s then add zeros as much as this number. Your program should look something like this:
int count=0;
List ll1=new ArrayList();
for(int i=0;i<ll.size();i++)
{
if((int)ll.get(i)!=10)
ll1.add(ll.get(i));
else
count++;
}
for(int j=0; j<count;j++)
ll1.add(0);
If count is number of 10's to add, use:
for(int j=0; j<count;j++){
ll1.add(8); // or ll1.add(0); ???
}
Few points to add to what others have mentioned above
I don't see any reason why you must define the output List to be static. When you define something(variables/functions) as static they are owned by the class rather that the objects and also it is a good programming practice not to change them using instance functions.What I mean is if you wish only to print there is no need of that output instance variable. You can directly print ll1.
Please use Generics in your code. When you know all you have in your list are integers specify it - Even in the function getVal(). I don't know how your code is compiling but you cannot cast Object to an int.
(int)ll.get(i)!=10
This code will fail. Try using Integer instead of int.
Your problem statement read replacing all 10's with 0's. So why are you adding 8 instead.It must be
ll1.add(0);
As other have specifies you need to add 0 as many time as your count is. So another loop is needed. Rest all look good.
Been a while since I used Java and was wondering if this was a decent or even correct way of setting this up.
FYI, userResults refers to a JDBI variable that isn't present in the code below.
Feel free to suggest a better method, thanks.
public class Stat
{
private int current;
private int max;
public int getCurrent() {return current;}
public void setCurrent(int current) {this.current = current;}
public int getMax() {return max;}
public void setMax(int max) {this.max = max;}
}
public class Character
{
Stat hp = new Stat();
Stat mp = new Stat();
}
Character thisCharacter = new Character();
// Set the value of current & max HP according to db data.
thisCharacter.hp.setCurrent((Integer) userResults.get("hpColumn1"));
thisCharacter.hp.setMax((Integer) userResults.get("hpColumn2"));
// Print test values
System.out.println (thisCharacter.hp.Current);
System.out.println (thisCharacter.hp.Max);
Correct? Well, does it work? Then it probably is correct.
Wether or not it is a decent way to do it then the answer is "maybe". It is hard to tell from what context this code is in. But there are some things you could keep in mind though:
In which class (or object rather) are the Stat set in? Do you feel is it the responsibility of the class to do this and know what database values to get them from? If not, consider making some kind of a class that does this.
Making chained calls such as thisCharacter.hp.setCurrent(...) is a violation of principle of least knowledge. Sometimes you can't help it, but usually it leads to kludgy code. Consider having something that handles all the logic surrounding the stats. In your code you may need a HealthStatsHandler that have methods such as loadStats(), saveStats(), and mutator actions such as takeDamage(int dmg) and revive(int health).
If you have trouble figuring things out if it has the correct object design, then study up on the SOLID principles. They provide nice guidelines that any developer should follow if they want to have code that is extensible and "clean".
This is not really a tree. It is not possible two have more than one layer of children.
Usually you define an interface let's call it Node where both Stat and Character implements it and the two children of Character would have the type Node.
I would consider creating the Stat objects seperately and passing them into Character, and making the character attributes private as follows:
public class Character
{
private Stat hp;
private Stat mp;
public Stat getHp() {return hp;}
public void setHp(Stat h) {this.hp = h;}
public Stat getMp() {return mp;}
public void setMp(Stat m) {this.mp = m;}
}
// Set the value of current & max HP according to db data.
Stat hp = new Stat();
hp.setCurrent((Integer) userResults.get("hpColumn1"));
hp.setMax((Integer) userResults.get("hpColumn2"));
Character thisCharacter = new Character();
thisCharacter.setHp(hp);
// do the same for mp
One additional simple step would be to create a Character constructor that would take an hp and an mp
I am trying to write a code to get the set of points (x,y) that are accessible to a monkey starting from (0,0) such that each point satisfies |x| + |y| < _limitSum. I have written the below code and have used static HashSet of members of Coordinate type (not shown here) and have written a recursive method AccessPositiveQuadrantCoordinates. But the problem is the members of the HashSet passed across the recursive calls is not reflecting the Coordinate members added in previous calls. Can anybody help me on how to pass Object references to make this possible? Is there some other way that this problem can be solved?
public class MonkeyCoordinates {
public static HashSet<Coordinate> _accessibleCoordinates = null;
private int _limitSum;
public MonkeyCoordinates(int limitSum) {
_limitSum = limitSum;
if (_accessibleCoordinates == null)
_accessibleCoordinates = new HashSet<Coordinate>();
}
public int GetAccessibleCoordinateCount() {
_accessibleCoordinates.clear();
Coordinate start = new Coordinate(0,0);
AccessPositiveQuadrantCoordinates(start);
return (_accessibleCoordinates.size() * 4);
}
private void AccessPositiveQuadrantCoordinates(Coordinate current) {
if (current.getCoordinateSum() > _limitSum) { return; }
System.out.println("debug: The set _accessibleCoordinates is ");
for (Coordinate c : _accessibleCoordinates) {
System.out.println("debug:" + c.getXValue() + " " + c.getYValue());
}
if (!_accessibleCoordinates.contains(current)) { _accessibleCoordinates.add(current); }
AccessPositiveQuadrantCoordinates(current.Move(Coordinate.Direction.East));
AccessPositiveQuadrantCoordinates(current.Move(Coordinate.Direction.North));
}
I will give points to all acceptable answers.
Thanks ahead,
Somnath
But the problem is the members of the HashSet passed across the recursive calls is not reflecting the Coordinate members added in previous calls.
I think that's very unlikely. I think it's more likely that your Coordinate class doesn't override equals and hashCode appropriately, which is why the set can't "find" the values.
As an aside, using static variables like this seems like a very bad idea to me - why don't you create the set in GetAccessibleCoordinateCount() and pass the reference to AccessPositiveQuadrantCoordinates, which can in turn keep passing it down in the recursive calls?
(As another aside, I would strongly suggest that you start following Java naming conventions...)
i don't see any problem with making the field _accessibleCoordinates non-static
and you should know that HashSet does not guarantee the same iteration order everytime, you could better use a LinkedList for that purpose...
and about pass by reference, i found this post very useful
java - pass by value - SO link
From what you are doing you would be updating _accessibleCoordinates in every recursive call correctly.
I am asking for help on self-help, which is kind of an oxymoron. How do I bug you nice folks less by solving more of my own problems?
I am in my last week of Java programming and I am having a huge hurdle with learning Java. I have read all the books but I keep getting hung up on tiny little issues. It is like trying to build a house of cards. I only know about the parts of the syntax and the uses that the book shows. When I am combining things, I run into horrible hurdles. I try for hours of tinkering to figure them out. The sun docs only show basic uses that don't seem to help
Here is what I would like:
When I am trying something and it doesn't work like the following manipulations of an array list, I want to find a place or program that can show examples code of things like adding an additional class instance to an arrayList. Where can I learn concisely about this without having to ask a question or 2 for every syntax error? Where is the Google for Java? Is there a program that will take your errors and show you how to fix them (or offer suggestions)?
/tmp/jc_4083/Inventory.java:101: incompatible types
found : RatedDVD[]
required: java.util.ArrayList
dvdlist = temp;
^
/tmp/jc_4083/Inventory.java:110: array required, but java.util.ArrayList found
if (p != dvdlist[i]) {
^
/tmp/jc_4083/Inventory.java:111: array required, but java.util.ArrayList found
temp[i-adj] = dvdlist[i];
^
/tmp/jc_4083/Inventory.java:115: incompatible types
found : RatedDVD[]
required: java.util.ArrayList
dvdlist = temp;
Here is my code for this class if anyone is interested in looking at it for me:
//Contruct inv and allow for methods add, get, size, sort, and value
import java.util.*;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
public class Inventory
{// class Inventory
private ArrayList<RatedDVD> dvdlist;// declare dvdlist as ArrayList of RatedDVD
private int numDVDs;
public Inventory()
{// method Inventory
dvdlist = new ArrayList<RatedDVD>();
}// end method
// add & get
public RatedDVD get(int i){return dvdlist.get(i);}// method get
public void add(DVD d){
dvdlist = dvdlist d;
sort();
}// method add
public double value()
{// method value
double total = 0.0;
for (int i = 0; i < dvdlist.size(); i++)
{// for every pass thru dvdlist add total
// [DEBUG] consider enhanced for
total += get(i).feeValue();
}
return total;
}// end method value
public void sort()
{// method sort
// [DEBUG] consider optimization
int n = dvdlist.size();
for (int search = 1; search < n; search++)
{// for do the following and increment till dvdlist has been searched
for (int i = 0; i < n-search; i++)
{// for step through comparison for entire dvdlist
if (dvdlist.get(i).getName().compareToIgnoreCase(dvdlist.get(i+1).getName()) > 0)
{// if swap necessary then swap
RatedDVD temp = dvdlist.get(i);
dvdlist.set(i,dvdlist.get(i+1));
dvdlist.set(i+1,temp);
}// end if swap
}// end for compareto
}// end outer for
}// end method sort
public int size(){return dvdlist.size();}// method size
public void save() {
save(true);
}
// save it to C:\data\inventory.dat
public void save(boolean saveagain) {
try {
BufferedWriter w = new BufferedWriter(new FileWriter("c:\\data\\inventory.dat"));
for (int i = 0; i < size(); i++) {
RatedDVD dvd = get(i);
w.write( dvd.getItem() + "\n");
w.write( dvd.getName() + "\n");
w.write( dvd.getRating() + "\n");
w.write( dvd.getUnits() + "\n");
w.write( dvd.getPrice() + "\n");
w.write( dvd.value() + "\n");
w.write( dvd.fee() + "\n");
w.write( dvd.feeValue() + "\n");
w.newLine();
}
// total value of it
//w.write( value() + "\n");
w.close();
} catch (Exception ex) {
if (saveagain) {
new File("c:\\data\\").mkdir(); // make file if doesn't exist
save(false);
}
}
}
public int search(String name) {
for (int i = 0; i < size(); i++) { // check if name string is equal
if (get(i).getName().equalsIgnoreCase(name)) return i;
}
return -1; // we didn't find anything
}
// add a new dvd to the end, increasing the array size
public void add(RatedDVD p) {
RatedDVD[] temp = new RatedDVD[dvdlist.size()+1];
for (int i = 0; i < dvdlist.size(); i++) {
temp[i] = dvdlist[i];
}
temp[temp.length-1] = p; // add it at the end
dvdlist = temp;
}
// remove a DVD from the array, and shrink the array size
public void delete(RatedDVD p) {
RatedDVD[] temp = new RatedDVD[dvdlist.size()-1];
int adj = 0;
for (int i = 0; i < dvdlist.size(); i++) {
if (p != dvdlist[i]) {
temp[i-adj] = dvdlist[i];
}
else adj = 1;
}
dvdlist = temp;
}
public int highestNumber() {
int numb = 0;
for (int i = 0; i < dvdlist.size(); i++) {
if (get(i).getItem() > numb) {
numb = get(i).getItem();
}
}
return numb;
}
}// end class inventory
The dvdlist is an ArrayList, which implements the Collection interface, not an Array (BTW, and this is known as the "program to an interface, not an implementation" principle, you should decalare dvdlist as a java.util.List):
private ArrayList<RatedDVD> dvdlist;// declare dvdlist as ArrayList of RatedDVD
Have a look at the methods on the Collection interface, you'll find everything you need for adding and removing elements.
So, to add a RatedDVD, you don't need to use a temporary array of RatedDVD that won't fit anyway into an ArrayList like you're doing here:
// add a new dvd to the end, increasing the array size
public void add(RatedDVD p) {
RatedDVD[] temp = new RatedDVD[dvdlist.size()+1];
for (int i = 0; i < dvdlist.size(); i++) {
temp[i] = dvdlist[i];
}
temp[temp.length-1] = p; // add it at the end
dvdlist = temp;
}
Instead, just call the add(Object o) method on dvdlist.
To delete a RatedDVD instance, use the remove(Object o) method on dvdlist.
For the search() method, consider using contains(Object o) on dvdlist.
If you need to iterate over a collection, use an Iterator:
for (Iterator iter = dvdlist.iterator(); iter.hasNext();) {
RatedDVD ratedDVD = (RatedDVD) iter.next();
//rest of the code block removed
}
Or even faster now with Java 5+ and Generics:
for (RatedDVD ratedDVD : dvdlist) {
// rest of the code here
}
Really, you need to dig the the Collection Framework.
The compiler errors seem to be quite descriptive of what you're doing wrong, but I can see why you might be confused about how to do it right. You seem to be misunderstanding how an ArrayList is meant to be used. If you look at the docs, you will see it has methods add() and remove() that do the operations you've created add() and delete() methods for. You're attempting to treat the ArrayList as if it is a raw array. Don't do that; use the methods provided by the API. Not only will this solve your errors, but it will make your code cleaner and clearer to future programmers.
Actually, the compiler error is very clear:
/tmp/jc_4083/Inventory.java:101: incompatible types
found : RatedDVD[]
required: java.util.ArrayList
dvdlist = temp;
It says "incompatible types" and that it expected a java.util.ArrayList but found instead a RatedDVD[].
Your problem is simply that, unlike in languages like Python, Java does not treat lists and arrays interchangeably. They are completely different things - arrays are special language-level constructs, while ArrayList is a class like any other.
So you cannot assign an array to a variably of type list. You either have to decide on using only one of these two types throughout your program, or you have to convert between them manually, using methods such as java.util.Arrays.asList() and List.toArray().
It seems that you're trying to do too advanced things too fast - you should probably look at Sun's Java tutorials first - though they are quite comprehensive and can also be used as a reference for looking up language details. There is also a section about conversion between collections and arrays.
I suggest you use an IDE (like Eclipse, entirely free). It will help you through the API syntax by making suggestions as you type, and show you errors when you type them, so that you can pinpoint exact syntax errors and ask about them. In terms of asking, that is what StackOverflow is for.
Others beat me to your specific syntax question, so I'm just limiting my answer to the general question of how you get help.
To resolve compiler errors, usually it's best to start with the first one and fix it first. After fixing that, the rest of the compiler errors might also be solved, or they might be different kinds of errors.
To understand what some compiler error means, there is an article called Compile and Runtime Errors in Java (PDF) that goes through different kinds of error messages and gives examples of what kind of code may cause them. And as for runtime error messages, Java Glossary has quite a big list of them. They also have a list of compile-time error messages.
So, your problem here is that you're trying to access an ArrayList like an array, which is incorrect because Java doesn't do stuff like that. You need to use list.get(i) to get the ith element in an Array. Similarly, when you tried to set an ArrayList variable to an array, the compiler got mad at you. You need to create a new ArrayList with the contents of temp and then set dvdlist to that, eg. dvdlist = new ArrayList<RatedDVD>(temp);.
As for your continued problems: There is an API Specification for Java which tells you basically how to use all the classes that are included in the Java API. For example, ArrayList is a generic collection which has certain methods and constructors that you need to use. Java does not have operator overloading, so you can't just access elements in a List using array syntax. Also, arrays are their own data type so you can't just treat an ArrayList as an array and vice versa.
It looks like you are confused about the difference between an array and an ArrayList. An array is a static list of elements, and is constructed using the [] symbols. An ArrayList is an object in the Collections system in Java that acts like a size-modifiable array - i.e. it can be indexed into, and can be added onto, inserted into, etc. They are not interchangable.
As to where you can look, etc. If this is your first programming experience, you are not alone. Many compiler errors are less than helpful. One suggestion I can give you that I learned through many years of trial and error - start small and build up. Get a main method that compiles. Then add the first little piece (creating a class for instance). Then add the next piece, and so on. Test as you go, etc. You can google for particular compiler errors - I have been surprised what I have found. Beyond that, a lot of it is trial and error - these are things you learn from experience, and a lot of the speed of "old hands" comes from the long experience of seeing what you can do wrong over and over again, not any sort of innate intelligence. I totally understand your frustration - I felt that way when I was starting out about 15 years ago now (but I was on Borland Pascal - yuck).
One of the biggest issues beginning programmers seem to have is not being able to read and interpret error messages very well.
You would be well served by carefully examining the errors that javac (or any compiler/interpreter) provides. Maybe even start by making some mistakes that you understand in your code (ie, assign an incorrect typed value to a variable, extend a loop beyond the bounds) and see how your compiler handles these.
Try to think in object oriented terms...
It looks to me that something (classwork, I guess) has pushed you into writing an object-oriented program but it's possible that you haven't yet accepted that you will need to think in those terms.
In Java most things are objects, but Java supports primitive types, and arrays of both. It's possible to program in Java in a flat, procedural, mutable way, but also possible to write in an object-oriented functional way. It's possible to do both and get confused, which is where you may be right now.
You are trying to mix the two styles. This isn't always a bad thing, but for coursework we can safely bet the farm that your instructor will want to see more objects and fewer arrays, unless those arrays are the private internal implementation of an object.
So think of the data structures as black boxes with methods, and then see how what you are doing is implementing one yourself.
You have probably been here, but these are the things that you can do with an ArrayList. And you have an ArrayList<RatedDVD> which further restricts what you can do with it. Try to understand this first, and then fix the program to work with the available operations on an ArrayList object.