...

View Full Version : A string conversion problem?



laland
10-13-2006, 06:05 PM
Hi,
now I am writing a very small and simple calculator program. The user may type in a string, eg: 123 / 345, then I suppose to convert this string into integer, and then try to calculate out the output. Does anyone know how to do the conversion. Do I hv to consider the case when when divide by 0? Do we have to throws exception in this case?

Below is a small partial code i wrote to extract the individual number out
eg. 123
/
345
. But I only can manage to print out the individual number using one line per word. How do I use it to convert it to integer and then divide them together?



//-----------------------------------------------------
// main method
//-----------------------------------------------------
public static void main (String [] args) {

//Calculator cal = new Calculator();


//int numAdd1 = 0, numAdd2 = 0;
int index = 0, numberOfCharacters,
beginIdx , endIdx;

String word, reply = " ";

Matcher matcher;
Pattern pattern = Pattern.compile(VALID_INPUT_PATTERN);

//System.out.print("");
Scanner sc = new Scanner(System.in);

String str = sc.nextLine();
numberOfCharacters = str.length();


while(true) {
if (str.equals(Q)) break;

if (str.matches(VALID_INPUT_PATTERN)) {
while ( index < numberOfCharacters ) {

//ignore leading blank spaces
while (index < numberOfCharacters &&
str.charAt(index) == BLANK) {

index++;
}

beginIdx = index;

//now locate the end of the word
while (index < numberOfCharacters &&
str.charAt(index) != BLANK) {

index++;
}

endIdx = index;

//System.out.println( beginIdx + " " + endIdx ); //TEMP


if (beginIdx != endIdx) {

//another word is found, extract it from the
//sentence and print it out

word = str.substring( beginIdx, endIdx );

System.out.println(word);


}
}
} else {
//System.out.println(INVALID_INPUT);
reply = INVALID_INPUT;
}

System.out.println(reply); break;
}

/

}
}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum