Test Questions

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

C:\Projects\Sandboxes\Tokenizer\Program.

cs
1 using System;
2 using System.Collections.Generic;
3
4 class Program
5 {
6
static void Main(string[] args)
{
7
8
Console.WriteLine("Please enter a simple equation such as 3 + 2");
9
10
// Read the input form the console
11
string input = Console.ReadLine();
12
13
// split the string into an array of strings using space as a
delimiter
14
string[] split = input.Split(' ');
15
16
// Tokenize each string into something meaningful
17
List<Token> tokens = new List<Token>();
18
foreach(var tok in split)
{
19
20
double numberValue;
21
if (double.TryParse(tok, out numberValue))
{
22
23
tokens.Add(new Number(numberValue));
}
24
25
else
{
26
27
if (tok.Equals("+"))
{
28
29
tokens.Add(new Operator() {isPlus = true});
}
30
31
if (tok.Equals("-"))
{
32
33
tokens.Add(new Operator() { isMinus = true });
}
34
35
if (tok.Equals("/"))
{
36
37
tokens.Add(new Operator() { isDivide = true });
}
38
39
if (tok.Equals("*"))
{
40
41
tokens.Add(new Operator() { isMultiply = true });
}
42
}
43
}
44
45
46
// Build an equation from the tokens
47
Equation equation = new Equation();
48
equation.left = (Number)tokens[0];
49
equation.op = (Operator)tokens[1];
50
equation.right = (Number)tokens[2];
51
52
// Reduce the equation to an
53
Number answer = equation.Reduce();
54
55
// Print the answer
56
Console.WriteLine("{0} = {1}", input, answer.value);
57
Console.ReadLine();
}
58
59
60
public abstract class Token

C:\Projects\Sandboxes\Tokenizer\Program.cs
2
{
61
62
// <snip common functionality>
}
63
64
65
/// <summary>
66
/// A token representing a floating point number
67
/// </summary>
68
public class Number : Token
{
69
70
public double value;
71
72
public Number(double value)
{
73
74
this.value = value;
}
75
}
76
77
78
/// <summary>
79
/// A token representing an operator
80
/// </summary>
81
public class Operator : Token
{
82
83
public bool isPlus;
84
public bool isMinus;
85
public bool isMultiply;
86
public bool isDivide;
}
87
88
89
/// <summary>
90
/// A simple equation with two operands and one operator
91
/// </summary>
92
public class Equation
{
93
94
public Number left;
95
public Operator op;
96
public Number right;
97
98
/// <summary>
99
/// An simple equation can be reduced to a number token by evaluating
it
100
/// </summary>
101
public Number Reduce()
{
102
103
double a = this.left.value;
104
double b = this.right.value;
105
106
if (this.op.isPlus)
{
107
108
return new Number(a + b);
}
109
110
111
if (this.op.isMinus)
{
112
113
return new Number(a - b);
}
114
115
116
if (this.op.isDivide)
{
117
118
return new Number(a / b);
}
119
120

C:\Projects\Sandboxes\Tokenizer\Program.cs
121
if (this.op.isMultiply)
{
122
123
return new Number(a * b);
}
124
125
126
return new Number(0);
}
127
}
128
129 }
130

You might also like