I need to use StringTokenizer, which I have, but something is wrong. I keep getting errors and I'm having some trouble finding out where. I know every time the program is executed, the while statement is not implemented. Here is my code so far:
PHP Code:
import java.util.*;
public class Calculator
{
private StringTokenizer tokenizer;
private String token;
public Calculator(String line)
{
tokenizer = new StringTokenizer(line);
token = tokenizer.nextToken();
}
public double Evaluate()
{
return Expression();
}
private double Primary()
{
double result;
if(token.equals(""))
{
token = tokenizer.nextToken();
result = Expression();
}
else
{
result = Double.valueOf(token).doubleValue();
}
token = tokenizer.nextToken();
return result;
}
private double Term()
{
double nextValue;
double result;
result = Primary();
while(token.equals("*"))
{
token = tokenizer.nextToken();
nextValue = Primary();
result *= nextValue;
}
while(token.equals("/"))
{
token = tokenizer.nextToken();
nextValue = Primary();
result /= nextValue;
}
return result;
}
private double Expression()
{
double nextValue;
double result;
result = Term();
while(token.equals("+"))
{
token = tokenizer.nextToken();
nextValue = Term();
result += nextValue;
}
while(token.equals("-"))
{
token = tokenizer.nextToken();
nextValue = Term();
result -= nextValue;
}
return result;
}
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
String line;
String choice = "y";
while(choice.equalsIgnoreCase("y"))
{
System.out.print("Enter an expression: ");
line = input.nextLine();
if(line.length() == 0)
{
System.out.println("Invalid input.");
System.out.println("Try again? (Y/N): ");
choice = input.nextLine();
if(choice.equalsIgnoreCase("n"))
{
System.out.println("Bye.");
System.exit(0);
}
}
Calculator expn = new Calculator(line);
System.out.println("Result is " + expn.Evaluate());
}
}
}
This is a sample output it should be:
Enter an expression: 4.45 + 1.0
Result is 5.45
Try again? y
Enter an expression: 2.3 – 10.77
Result is -8.47
Try again? y
Enter an expression: 5.3
Input error
Try again? y
Enter an expression: 5.4 * 2.7.7
Input error
Try again? y
Enter an expression: 6.0 + * 3.0
Input error
Try again? n
Bye.
This is what I get:
Enter an expression: 4.45 + 1.0 =
Result is 5.45
Enter an expression: 2.3 - 10.77 =
Result is -8.469999999999999
Enter an expression:
..............it repeats until manually terminating the program.
Any help would be appreciated. Thanks in advance.
Bookmarks