Sign in to follow this  
jdub

Problem with array printing function: Java

Recommended Posts

given:
package Fruit;


public class Fruit {
   public String name;
   public int quantity;
   public float price;
   
   public Fruit(String _name , int _quantity , double _price){
    _name = name;
    _quantity = quantity;
    _price = price;
   }
   
}

and

package Fruit;

import java.util.*;

public class main {
    
   
    public static void main(String args[]){
        Fruit a[] = new Fruit[10];
        
        for (int i = 0 ; i < a.length ; i++ ){
            a[i] = new Fruit("Fruit" , 1 , 1.99);
        }
        
        printFruit(a[]); 
        
    }
    
    public void printFruit(Fruit []argfruit){
        int argfruitsize = argfruit.length;
        for (int i = 0 ; i < argfruitsize; i++){
            System.out.println("/n");
            System.out.println("Fruit name:");
            System.out.println(argfruit[i].name);
            System.out.println();
            System.out.println("Fruit price:");
            System.out.println(argfruit[i].price);
            System.out.println();
            System.out.println("Fruit quantity");
            System.out.println(argfruit[i].quantity);
           
        }
       
        
    }
    
    
}

why is there an error when I try to call the printFruit() function. "a" is of type "Fruit" and is an array, yet an error when compiled reports: main.java:15: '.class' expected printFruit(a[]); 1 error BUILD FAILED (total time: 0 seconds) I'm stumped. Help is appreciated

Share this post


Link to post
Share on other sites
Two things I see looking over this quickly:

1. I think you want name = _name; (this goes for all of them) in your Fruit class so you actually assign the passed in variables instead of using the defaults later.
2. I'm not a 100% sure, but don't use "main" as the name of your class. Change it to something like FruitTester in FruitTester.java and try recompiling.

Share this post


Link to post
Share on other sites
it should be "name = _name" , cause name is the the variable thats remembered. same thing with quantity and price.

Then I would take a different approach to the print function. I'd rather put the print in the fruitclass:

printFruit(){
System.out.println("/n");
System.out.println("Fruit name:");
System.out.println(name+"\n");
System.out.println("Fruit price:");
System.out.println(price+"\n");
System.out.println("Fruit quantity");
System.out.println(quantity+"\n");

}
and something like this in the mainclass, insteadof printFruit(a[]);

for (int i = 0; i<a.length; i++){
a[i].printFruit();
}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this