mardi 28 juin 2016

Java: Program not behaving correctly

I know this is probably Nth alike question, but I have been through this site several times now and I still can't find an answer to this. It is especially bugging, for someone like me, who is a month long in Java and still has a lot to learn. Anyways, I am trying to create a program for user-inputing an info on books (Name, Author, Publishing year and price). And then I want to be able to get a list of the books' names published after 2000 and their average price. At first, I thought of using arrays in an array, but after going through similar questions I chose to make a Book class:

public class Books {
 public static String name;
 public static String author;
 public static int year;
 public static float price;
 public static float sum = 0.0F;
 public static float avrg = 0.0F;   

I don't know if the following are necessary, but I did it as I've seen it in a lot of examples:

public String getName () {
            return name;
        }
        public String getAuthor () {
            return author;
        }
        public int getYear () {
            return year;
        }
        public float getPrice () {
            return price;
        }

Then, I am trying to take the user input and store my new objects in an array.

public static void main(String[] args) {
    System.out.println("Please enter details for five books!");     
    Scanner in = new Scanner (System.in);
    Books [] book = new Books[5];
    int i = 0;
    int j = 0;
    int count = 0;

    for (i=0; i < book.length; i++) {
        System.out.println("Enter Book Title, Author Last Name, Year and Price:");
        String name = in.next();
        String author = in.next();
        int year = in.nextInt();
        float price = in.nextFloat();
        }

And here I want to find the exact books and calculate their average price:

for (j=0; j<book.length; j++){
        if (Books.year >= 2000) {
            System.out.println("Books published after 2000:"+ Books.name);
            sum = sum + Books.price;
            count = count + 1;
        }       
}
    avrg = sum/count;
    System.out.println("Average price of books published after 2000:"+avrg);

Everything seems to be running smoothly till the part I want the names of the books (and average price) published. I get this as a result:

Please enter details for five books!
Enter Book Title, Author Last Name, Year and Price:
...
Average price of books published after 2000:NaN

It doesn't even show the names.I'm quite confused and I have no idea if this is the best way to do what I want to do. I will appreciate some help, I've been stuck on this for 2 days now.

Aucun commentaire:

Enregistrer un commentaire