views:

277

answers:

9

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
+3  A: 

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.

rmeador
would you even make a method or just use those built in operation from the caller?
lazfish
I think best practices would have your class implement those methods and simply call (delegate to) the appropriate method on its dvdlist member. The user of the Inventory class shouldn't need to know that it has a member of type ArrayList.
rmeador
+2  A: 

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.

Michael Borgwardt
A: 

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.

Ibrahim
A: 

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).

aperkins
+1  A: 

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.

Yishai
Cool. I have eclipse downloaded but it was not intuitive, that is once I got the program up, I accidentally skipped the confusing fancy wizard frontend and the when I got the next screen pulled up it was not apparent what to do next. I abandoned it thinking it would require too much learning (I admit I didn't plug away at it like I should have tried)
lazfish
IDE's suffer from trying to please a larger crowd of advanced programmers, and expecting you to have some idea of how to structure a project, but just go to create a new project in Eclipse (File->New->Project) and choose a java project. And pick the defaults as much as possible. Its good enough for the first time.
Yishai
A: 

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.

Matthew Schinckel
+1  A: 

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.

Esko Luontola
A: 

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.

DigitalRoss
So there is no magic button!? Someone should make a magic button. Or like a calculator. With my calculator I can forget my multiplication tables. Thats what I wish I had. A calculator BUT with a link to the multiplication tables. Because this is due tomorrow. I want to learn more. just. not. right. now. Studentoffortune.com is too hands-off for me. I like programming even though I also hate it. I'm sure you know what I mean.
lazfish
If you put a bounty on your question I will do your homework for you, otherwise "yes, this is my final answer". :-)
DigitalRoss
lol. I got it done. Took hours but hey it works
lazfish
+5  A: 

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.

Pascal Thivent