1

I've been struggling with a method that is meant to search through an array of objects and return a specific value.In my driver class, I read the periodic table csv file and split the variables read in each line send it to an object of the Element class. In my periodic table class, I create an array of Element objects that is meant to hold each element that is read from the driver. My current "findElement" method results in a nullpointer exception and I'm not sure if my array of objects is doing exactly what I want it to. Feel free to throw out suggestions. Below are my classes:(i went back to a driver only program)

Driver:This class opens an input file and splits a line into 7 different variables which are then sent to an Element class object.

public class PeriodicTableDriver
{
public static void main(String[] args)
{
    Scanner keyboard= new Scanner(System.in);
    Scanner inputStream=null;
    String elementName="";
    String atomicNumber="";
    String symbol="";
    double boilingPoint=0;
    double meltingPoint=0;
    double density=0;
    double molecularWeight=0;
    int choice=0;
    String fileName1= "PeriodicTableData.csv";
    String fileName2= "MolecularWeightInput.txt";
    PeriodicTable periodicTable= new PeriodicTable();


try
{
    inputStream=new Scanner(new File(fileName1));
}
catch(FileNotFoundException e){
    System.out.println("Error opening the file.");
    System.exit(0);
}
    int count=0;
String title=inputStream.nextLine();
while(inputStream.hasNext()){
    String periodicInfo=inputStream.nextLine();
    String[] PeriodicTableData= periodicInfo.split(",");
    elementName=PeriodicTableData [0];
    atomicNumber= PeriodicTableData [1];
    symbol= PeriodicTableData [2];
if (PeriodicTableData[3].equals(""))
      boilingPoint = 0;
else
       boilingPoint = Double.parseDouble(PeriodicTableData[3]);
if (PeriodicTableData[4].equals(""))
       meltingPoint = 0;
else
       meltingPoint = Double.parseDouble(PeriodicTableData[4]);
if (PeriodicTableData[5].equals(""))
     density = 0;
else
       density = Double.parseDouble(PeriodicTableData[5]);
if (PeriodicTableData[6].equals(""))
     molecularWeight = 0;
else
       molecularWeight = Double.parseDouble(PeriodicTableData[6]);
count++;
Element element= new Element(count,elementName,atomicNumber,symbol,boilingPoint,meltingPoint,density,molecularWeight);
    periodicTable.readPeriodicTableInfo(element);
    periodicTable.displayElement(symbol);
}
try
{
    inputStream=new Scanner(new File(fileName2));
}
catch(FileNotFoundException e){
    System.out.println("Error opening the file.");
    System.exit(0);
}
while(inputStream.hasNextLine()){
}

}

}

Element class: holds all of the variables read from the driver and has a toString method for formatting them

public class Element
{
    String elementName;
    String atomicNumber;
    String symbol;
    double boilingPoint;
    double meltingPoint;
    double density;
    double molecularWeight;
    int count;
public Element(int count, String elementName, String atomicNumber, String symbol,
double boilingPoint, double meltingPoint, double density,
double molecularWeight)
{
    super();
    this.count=count;
    this.elementName = elementName;
    this.atomicNumber = atomicNumber;
    this.symbol = symbol;
    this.boilingPoint = boilingPoint;
    this.meltingPoint = meltingPoint;
    this.density = density;
    this.molecularWeight = molecularWeight;
}
public String toString(){
    String element = "Element name:     " + elementName
            + "\nAtomic Number:    " + atomicNumber
            + "\nSymbol:           " + symbol;
     if (boilingPoint == 0)
     {
             element = element + "\nBoiling Point:    unknown";
     }
     else
     {
             element = element + "\nBoiling Point:    " + boilingPoint + " K";
     }
     if (meltingPoint == 0)
     {
             element = element + "\nMelting Point:    unknown";
     }
     else
     {
             element = element + "\nMelting Point:    " + meltingPoint + " K";
     }
     if (density == 0)
     {
             element = element + "\nDensity:    unknown";
     }
     else
     {
             element = element + "\nDensity:    " + density + " g/L";
     }
     element=element+"\nMolecular Weight:     " + molecularWeight + "g/mole";
     return element;
}

/**
* @return the elementName
*/
public String getElementName()
{
    return elementName;
}
/**
* @return the atomicNumber
*/
public String getAtomicNumber()
{
    return atomicNumber;
}
/**
* @return the symbol
*/
public String getSymbol()
{
    return symbol;
}

/**
* @return the boilingPoint
*/
public double getBoilingPoint()
{
    return boilingPoint;
}
/**
* @return the meltingPoint
*/
public double getMeltingPoint()
{
    return meltingPoint;
}
/**
* @return the density
*/
public double getDensity()
{
    return density;
}
/**
* @return the molecularWeight
*/
public double getMolecularWeight()
{
    return molecularWeight;
}
/**
* @return the count
*/
public int getCount()
{
    return count;
}

}

PeriodicTable class: holds methods that will fulfill the menu items

public class PeriodicTable
{
    private final static int ARRAY_SIZE= 120;
    private Element[] elements;
    private int count=110;
    Scanner keyboard= new Scanner(System.in);

public PeriodicTable(){
      elements = new Element[ARRAY_SIZE];
}

public void readPeriodicTableInfo(Element element){
 for(int i=0; i<elements.length;i++){
    elements[i]=element;
    System.out.println(elements[i].toString());


}
}
public void displayMenu(){
    System.out.println("1. Display information for all elements in the Periodic Table");
    System.out.println("2. Display information for one element");
    System.out.println("3. Display particle information for one element"); 
    System.out.println("4. Display the element with the highest boiling point");
    System.out.println("5. Display the element with the lowest melting point");
    System.out.println("6. Display the molecular mass calculations for elements in file");
    System.out.println("7. Quit");
    System.out.print("Please enter your choice: ");
}
public int findElement(String symbol){
    System.out.println("Enter element symbol: ");
    String elementSymbol=keyboard.next();
for(int i=0; i<elements.length;i++){
if(elementSymbol.equalsIgnoreCase(elements[i].getSymbol())){
     return i;
}
}

     return -1; 
}

public void displayElement(String symbol){
    System.out.println();
    System.out.println(elements[findElement(symbol)].toString());
}
}
5
  • 1
    So, what's the problem? Commented Dec 4, 2015 at 20:02
  • I'm trying to create a method that searches through an array (findElement) and returns the index as to where this element is located. Then, in my displayElement method, it will print the element at that index formatted toString. Commented Dec 4, 2015 at 22:51
  • Please don't deface your question. Question rolled back. Commented Dec 5, 2015 at 12:14
  • Ditto on the above -- please stop defacing your question. I've notified the moderators of your actions. Commented Dec 5, 2015 at 20:44
  • @cubswin234 Please stop defacing your question. Commented Dec 6, 2015 at 0:14

1 Answer 1

2

You've got lots of issues in that code, not the least of which your PeriodicTable looks like it will hold multiple references to one and only one Element.

but as to your problem:

  • Your findElement method should have no println statements,
  • it should have no keyboard.next() or keyboard statements at all.
  • it should simply use the String that was passed in via its parameter and search the elements array for the matching element.
  • You'll also have to fix how it fills up the array so that each array item holds a unique element.

So findElement should be much simpler, something like:

public int findElement(String symbol){
    for(int i=0; i<elements.length;i++) {
         if(symbol.equalsIgnoreCase(elements[i].getSymbol())){
               return i;
         }
    }
    // I'd throw an exception here if no element is found
}

Even better would be to have the method return the found Element object and not the int array index.

Also, a side recommendation: Please look up and try to follow Java code formatting rules. By following these rules, others will more easily be able to read and understand your code, and then be able to help you. If you are using most IDE's they can help you format your code correctly for you.

Edit: This appears to be the most broken method of all:

public void readPeriodicTableInfo(Element element){
    for (int i=0; i<elements.length;i++) {
        elements[i]=element;
        System.out.println(elements[i].toString());
    }
}

Let's look at what it does: it loops through the entire elements array, placing the element that is passed into this method into every item within the array, something that I really don't think you want to have happen. Instead, you should add the element passed in to one and only one item in the array. This would be best performed by changing elements from an array to an ArrayList<Element>, and then you could simply call the ArrayList add method. If you can't use that, then you're going to have to use an index variable to keep track of how many elements have already been added, and then add the latest one into the next empty array slot.

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

1 Comment

The index variable is "count" in the driver. Is this as simple as replacing "elements.length" with "element.getCount()" and deleting "elements[i]=element;"?

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.