0

I have a program that uses a .dat file to look up periodic elements. However, every time I try to find the element by the number or name I keep getting that it could not be found.

Also I have an issue with a NumberFormatException; null everytime I use option 3.

Any help would be of great assistance!!!

import java.util.Scanner;
import java.util.Arrays;
import java.io.File;
import java.io.FileNotFoundException;

class PeriodicElement{
    private int atomicNum;
    private float atomicWeight;
    private String abbreviation , name;

PeriodicElement(int atomicNum , String abbreviation , String name , float atomicWeight){
    this.atomicNum    = atomicNum;
    this.abbreviation = abbreviation;
    this.name         = name;
    this.atomicWeight = atomicWeight;
}

public int getNumber(){
    return atomicNum;
}

public String getAbb(){
    return abbreviation;
}

public String getName(){
    return name;
}

public float getWeight(){
    return atomicWeight;
}

public String toString(){
    return String.format("%3d %-3s %-20s %5.2f", atomicNum, abbreviation, name, atomicWeight);
}
}
class PeriodicTable{
    private String fileName = "periodictable.dat";
    private String[][] table = new String[200][4];

PeriodicTable(String fileName){
    readTable(fileName);
}

public String[][] readTable(String fileName){
    Scanner inFile = null;
    try{
        inFile = new Scanner(new File(fileName));
    }catch(FileNotFoundException nf){
        System.out.println(fileName + " not found");
        System.exit(0);
    }

    table = new String[200][4];
    int i = 0;
    while (inFile.hasNext() && i < table.length){
        int number           = inFile.nextInt();
        String abbreviation  = inFile.next();
        String name          = inFile.next();
        float weight         = inFile.nextFloat();
        String strNumber = String.valueOf(number);
        String strWeight = String.valueOf(weight);
        table[i][0] = strNumber;
        table[i][1] = abbreviation;
        table[i][2] = name;
        table[i][3] = strWeight;
        i++;
    }
    inFile.close();
    return table;
}

public int getNumberOfElements(){
    int counter = 0;
    for(int i = 0; i < table.length; i++){
        if (table[i][0] != null){
            counter++;
        }
    }
    return counter;
}

public String findElement(String number){
    for(int i = 0; i < table.length; i++){
        if(number == table[i][0]){
            String strAtomicNum       = table[i][0];
            String abbreviation       = table[i][1];
            String name               = table[i][2];
            String strAtomicWeight    = table[i][3];

            int atomicNumber   = Integer.parseInt(strAtomicNum);
            float atomicWeight = Float.parseFloat(strAtomicWeight);

            PeriodicElement element = new PeriodicElement(atomicNumber , abbreviation,
                                      name , atomicWeight);
            return element.toString();
        }
    }
    return null;
}

public String findAbbreviation(String abbreviation){
    for(int i = 0; i < table.length; i++){
        if(abbreviation == table[i][1]){
            String strAtomicNum      = table[i][0];
            String abbreviation1     = table[i][1];
            String name              = table[i][2];
            String strAtomicWeight   = table[i][3];

            int atomicNumber   = Integer.parseInt(strAtomicNum);
            float atomicWeight = Float.parseFloat(strAtomicWeight);

            PeriodicElement element = new PeriodicElement(atomicNumber , abbreviation1,
                                      name , atomicWeight);
            return element.toString();
        }
    }
    return null;
}

public String printTable(){
    System.out.println("### $$$ $$$$$$$$$$$$$$$$$$$$ ###.##\n");
    for(int i = 0; i < table.length; i++){
        String strAtomicNum      = table[i][0];
        String abbreviation1     = table[i][1];
        String name              = table[i][2];
        String strAtomicWeight   = table[i][3];

        int atomicNumber   = Integer.parseInt(strAtomicNum);
        float atomicWeight = Float.parseFloat(strAtomicWeight);

        PeriodicElement element = new PeriodicElement(atomicNumber , abbreviation1,
                                  name , atomicWeight);
        String elementInfo = element.toString();
        if (table[i][0] != null){
            System.out.println(elementInfo);
        }
    }
    return null;
}

public static void main(String[] args){
    System.out.println("Periodic Table by Ronald Lencevicius.\n");

    PeriodicTable table = new PeriodicTable("periodictable.dat");
    int numberElements = table.getNumberOfElements();
    System.out.println("Number of elements: " + numberElements + "\n");

    Scanner kb = new Scanner(System.in);
    Scanner kb1 = new Scanner(System.in);
    Scanner kb2 = new Scanner(System.in);
    int choice = 0;
    while(choice != 4){
        System.out.println("1. Search atomic number");
        System.out.println("2. Search abbreviation");
        System.out.println("3. Print table");
        System.out.println("4. Exit\n");
        System.out.println("Enter a choice?");

        choice = kb.nextInt();

        if(choice == 1){
            System.out.println("Enter atomic number: ");
            String elementNum = kb1.next();

            String element = table.findElement(elementNum);
            if(element != null){
                System.out.println("### $$$ $$$$$$$$$$$$$$$$$$$$ ###.##\n" + 
                           element);
            }else{
                System.out.println("Not found");
            }
        }else if(choice == 2){
            System.out.println("Enter abbreviation: ");
            String abbrev = kb2.next();

            String element = table.findAbbreviation(abbrev);
            if(element != null){
                System.out.println("### $$$ $$$$$$$$$$$$$$$$$$$$ ###.##\n" + 
                           element);
            }else{
                System.out.println("Not found");
            }
        }else if(choice == 3){
            table.printTable();
        }else if(choice == 4){
            System.exit(0);
        }
    }
}
}

Here is the .dat file.

1    H   Hydrogen    1.00794
2    He      Helium  4.002602
3    Li      Lithium     6.941
4    Be      Beryllium   9.012182
5    B   Boron   10.811
6    C   Carbon  12.0107
7    N   Nitrogen    14.0067
8    O   Oxygen  15.9994
9    F   Fluorine    18.9984032
10   Ne      Neon    20.1797
11   Na      Sodium  22.98976928
12   Mg      Magnesium   24.3050
13   Al      Aluminum    26.9815386
14   Si      Silicon     28.0855
15   P   Phosphorus  30.973762
16   S   Sulfur  32.065
17   Cl      Chlorine    35.453
18   Ar      Argon   39.948
19   K   Potassium   39.0983
20   Ca      Calcium     40.078
21   Sc      Scandium    44.955912
22   Ti      Titanium    47.867
23   V   Vanadium    50.9415
24   Cr      Chromium    51.9961
25   Mn      Manganese   54.938045
26   Fe      Iron    55.845
27   Co      Cobalt  58.933195
28   Ni      Nickel  58.6934
29   Cu      Copper  63.546
30   Zn      Zinc    65.38
31   Ga      Gallium     69.723
32   Ge      Germanium   72.64
33   As      Arsenic     74.92160
34   Se      Selenium    78.96
35   Br      Bromine     79.904
36   Kr      Krypton     83.798
37   Rb      Rubidium    85.4678
38   Sr      Strontium   87.62
39   Y   Yttrium     88.90585
40   Zr      Zirconium   91.224
41   Nb      Niobium     92.90638
42   Mo      Molybdenum  95.96
43   Tc      Technetium  0
44   Ru      Ruthenium   101.07
45   Rh      Rhodium     102.90550
46   Pd      Palladium   106.42
47   Ag      Silver  107.8682
48   Cd      Cadmium     112.411
49   In      Indium  114.818
50   Sn      Tin     118.710
51   Sb      Antimony    121.760
52   Te      Tellurium   127.60
53   I   Iodine  126.90447
54   Xe      Xenon   131.293
55   Cs      Cesium  132.9054519
56   Ba      Barium  137.327
57   La      Lanthanum   138.90547
58   Ce      Cerium  140.116
59   Pr      Praseodymium    140.90765
60   Nd      Neodymium   144.242
61   Pm      Promethium  0
62   Sm      Samarium    150.36
63   Eu      Europium    151.964
64   Gd      Gadolinium  157.25
65   Tb      Terbium     158.92535
66   Dy      Dysprosium  162.500
67   Ho      Holmium     164.93032
68   Er      Erbium  167.259
69   Tm      Thulium     168.93421
70   Yb      Ytterbium   173.054
71   Lu      Lutetium    174.9668
72   Hf      Hafnium     178.49
73   Ta      Tantalum    180.94788
74   W   Tungsten    183.84
75   Re      Rhenium     186.207
76   Os      Osmium  190.23
77   Ir      Iridium     192.217
78   Pt      Platinum    195.084
79   Au      Gold    196.966569
80   Hg      Mercury     200.59
81   Tl      Thallium    204.3833
82   Pb      Lead    207.2
83   Bi      Bismuth     208.98040
84   Po      Polonium    0
85   At      Astatine    0
86   Rn      Radon   0
87   Fr      Francium    0
88   Ra      Radium  0
  • Just try to println the values of `strAtomicNum` and `strAtomicWeight` to see their value when they cannot be converted to int/float. – StephaneM Jun 03 '16 at 12:30
  • can you please share your table which returns from readTable() method? – erolkaya84 Jun 03 '16 at 12:31
  • just added it to the post –  Jun 03 '16 at 12:34
  • Also, I just checked and I think my program returns null in the findElement method even when I input a valid number. It doesn't even print stuff that i put in to check in the for loop. –  Jun 03 '16 at 12:36
  • 1
    Hint: the fact that you are repeating this code `String strAtomicNum = table[i][0] ...` over and over again ... is an excellent indication to you ... that you should handle that differently. Meaning: you could push those 4 values ... into a little class itself. Your current approach is very much "procedural" - you define a "data layout"; and then you write code around that layout. A real OO design tries to **model** classes that combine "data and behavior" instead. – GhostCat Jun 03 '16 at 12:38
  • I'm kind of out of time with this. I'm too exhausted to think of another way of rewriting it... I already rewrote this about 5 times. I just don't understand why I end up with null values in the findElement and findAbbreviation methods. –  Jun 03 '16 at 12:42
  • This is a big chunk of code to work through for us. You'll probably get more help if you post a minimal working example instead: remove all code that is not necessary to reproduce the problem. Make sure to test whether that program still fails of course! – Oebele Jun 03 '16 at 12:43

1 Answers1

2

Java works with references (except for primitives) so when you do

if(number == table[i][0])

in findElement you are comparing the memory address of the two variables, where you want to compare their value. Change that into

if(number.equals(table[i][0]))

and the same with findAbbreviation

dtortola
  • 768
  • 4
  • 6
  • Thank you so much!!!!!! I've been at this all night... You really saved me. –  Jun 03 '16 at 12:54
  • No problem. However, when you have more time, you should do as Jägermeister said and use a Class instead of an String[] for each line of the file. That way, if for any reason the file changes, you only have to change the method that reads it and makes that Class instances, instead of all those methods – dtortola Jun 03 '16 at 12:58
  • Yeah, I guess you live and learn. I'm honestly not that good and classes give me a lot of trouble. I'll make sure to practice though. –  Jun 03 '16 at 13:10