I'm trying to write a method on java that takes a string and returns the first character to a char variable and the numbers i the string to a integer variable. The strings will always follow the format of one character and one/two numbers (eg C25 or C5). It compiles but when i call the method I get the error: Error: cannot find symbol - variable C5. C5 being the string I input.
import java.lang.*;
public class Term
{
private char element;
private int atoms;
// creates a Term with the provided values
public Term(char element, int atoms)
{
this.element = element;
this.atoms = atoms;
}
// creates a Term by parsing s
// e.g. "H20" would give element = 'H', atoms = 20
public Term(String s)
{
if (s.length() > 1) {
int x = Integer.parseInt(s);
char y = s.charAt(0);
this.atoms = x;
this.element = y;
} else {
this.element = s.charAt(0);
}
}
// turns the Term into a String
// e.g. element = 'C', atoms = 4 would give "C4"
public String display()
{
String rtnstr;
rtnstr = "";
if (atoms > 1 || atoms != 0) {
String str1 = Character.toString(element);
String str2 = String.valueOf(atoms);
rtnstr = str1 + str2;
} else if (atoms == 1) {
rtnstr = Character.toString(element);
} else if (atoms == 0) {
rtnstr = "Error, zero atoms present in term.";
}
return rtnstr;
}
// returns the current value of element
public char getElement()
{
return element;
}
// returns the current value of atoms
public int getAtoms()
{
return atoms;
}
}
Thanks
Seeing that the format will always be one character and one/two numbers (eg C25 or C5) you can do this
public Term(String s) {
this.element = s.charAt(0);
this.atoms = Integer.parseInt(s.subString(1));
}