0
  1. I defined "class Product" with fields "price" and "sales".
  2. Then, I created an array of type "Product": Product productArray[] = new Product[100]
  3. Then I filled this array with data from an excel table containing 100 rows and 2 columns (column A: "price" , column B: "sales")

I want to directly access the price of different products, say the price of the product in row 97. That is, I would like to do something like Double variable = productArray[97].price

Is there a way of doing this in java ?

Help would be very much appreciated ! Thank you in advance.

2
  • 1
    Well, have you tried Double variable = productArray[97].price? Sounds like it should work. Maybe productArray[97].getPrice()? Also, beware that array are 0 indexed: row 1 is productArray[0]. Commented Sep 7, 2015 at 20:18
  • Have you tried it? It should work if price has the right access modifier. Commented Sep 7, 2015 at 20:23

1 Answer 1

1

You should create getter and setter methods for your variables as encapsulation is a good OOP concept to protect your variables.

Consider the following scenario which will be similar to what you are doing, you have a Product class.

I will use an alien class:

public class Alien{

//Properties of aliens
int numOfFingers;
String name;
String color;

public Alien(int num, String name, String color)
{
    this.numOfFingers = num;
    this.name = name;
    this.color = color;
}       

}//End of alien class

The class containing the array:

public class DetailExtractor {

//Arraycontaining alien objects
Alien[] alienRegister = new Alien[100];

public static void main(String[] args){
    //Populating the array
    alienRegister[0] = new Alien(3, "Zorg", "Blue");
    alienRegister[1] = new Alien(5, "Chad", "Purple");


    //Retrieving a property, say name of second alien...

    System.out.println(alienRegister[1].name);

}

}
Sign up to request clarification or add additional context in comments.

1 Comment

so my code should actually work ... then it didn't compile because of some other issue ... I thought it didn't work because of the "productArray[97].price"-part.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.