TeamJava Forum
[ Read Responses | Post a New Response | Return to the Index ]
[ Previous | Next in Thread | Next ]
Chemical Forumulae
Posted by Morris on Wednesday, 20 August 2003, at 9:44 a.m.
Hi....I was wondering if any-one could help me with this problem I'm having.
Basically what I'm trying to do is create a program that allows the user to enter a chemical forumulae such as CaCO3
and the output to that should be, C is the symbol for Carbon and there is 1 atom of this element, Ca for Calcium (1 atom),
O for Oxygen (3 atoms)
There is a text file with all the elements in it.
eg of text file:
Ag Silver
Al Aluminium
Au Gold
C Carbon
Ca Calcium
etc...
Below I've created a program that doesn't use a file to read the data from, I put some of the contents of the file in
a string. ((I have to change this later))
Anyway, I need to use an IDE to run the program...through some help from some java tutorials, I've created a program that
almost works. However, I made the program so It has to have 'arguments'.
IE... if I type in; java ChemicalFormulae CaCO3 ((In DOS MODE)) brings out the right result.
and if I also click on the run tab, then click on 'arguments' and type in 'H2O', it would bring out the right result.
You see...the program needs parametres to run successfully...
import java.util.regex.*;
public class ChemicalFormulae {
/* names should be loaded dynamically from that file */
private String[] names = {"H", "C", "Ca", "O"};
private Matcher matcher = null;
private Pattern pattern = null;
static java.io.PrintStream p = System.out;
public static void main(String[] args) {
ChemicalFormulae inoh = new ChemicalFormulae();
for (int i = 0; i if (inoh.isValid(args[ i])) {
inoh.check(args[ i]);
} else {
System.out.println("Illegal formula: " + args[ i]);
}
}
}
public ChemicalFormulae() {
String regex = "([A-Z][a-z]?+)([0-9]*+)";
pattern = Pattern.compile(regex);
matcher = pattern.matcher("");
}
/* Element name needs real solution, current implementation is too static ;) */
private String getElementName(String s) {
if ("H".equals(s)) {
return "Hydrogen";
} else if ("O".equals(s)) {
return "Oxygen";
} else {
return s;
}
}
private String getElementCount(String s) {
if ("".equals(s)) {
return "1";
} else {
return s;
}
}
private static void order() {
p.println("Would you like fries with that?");
}
public boolean isValid(String formula) {
String regex = "((";
for (int i = 0; i regex += (i == 0 ? "(" : "|(") + names[ i] + ")";
}
regex += "){1}[0-9]*)+";
return formula.matches(regex);
}
/* check needs better name and should be redesigned to just collect data */
public void check(String formula) {
int end = 0;
matcher = matcher.reset(formula);
while (matcher.find(end)) {
end = matcher.end();
System.out.println("Element " + getElementName(matcher.group(1))
+ " occured " + getElementCount(matcher.group(2)) + " time(s)");
}
}
}
Responses
Post a New Response
The TeamJava Forum is maintained with WebBBS 2.24.