-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCellFormula.java
More file actions
77 lines (77 loc) · 2.91 KB
/
CellFormula.java
File metadata and controls
77 lines (77 loc) · 2.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*
* Cell is a unit of the spreadsheet so that is handles all the changes to the cell values according to the location.
*/
public class CellFormula extends Cell
{
public CellFormula(int r, int c)
{
super(r, c);
}
public String setCellIndividualFormula(String input) throws NumberFormatException, StringIndexOutOfBoundsException
{
input = input.substring(2, input.length()-1); //gets rid of partentheses and spaces
String[] inputArray = input.split(" ");
if (numOfOperation(input) == 0)
{
System.out.println("Invalid Input: Not a valid Formula. Doesnt have enough spaces or only one operation.");
return "<empty>";
}
try
{
String nextString = input.substring(0, input.indexOf(" "));
double finalValue = finalValue = Double.parseDouble(input.substring(0, input.indexOf(" ")));
while(input.length() > 1)
{
char operator = input.charAt(input.indexOf(" ") + 1);
input = input.substring(input.indexOf(operator)+2);
double nextValue = Double.parseDouble(input.substring(0, input.indexOf(" ")));
input = input.substring(input.indexOf(" "));
if(operator == '+')
{
finalValue += nextValue;
}
else if (operator == '-' && input.charAt(input.indexOf(operator) + 1) == ' ')
{
finalValue -= nextValue;
}
else if (operator == '*')
{
finalValue *= nextValue;
}
else if (operator == '/')
{
finalValue /= nextValue;
}
else
{
System.out.println("Invalid Input: Invalid operation"); //not a valid operator or forgot an operator
return "<empty>";
}
}
String finalValueString = "" + finalValue;
return finalValueString;
}
catch(NumberFormatException err)
{
System.out.println("Invalid Input: Not every value is a valid number");
return "<empty>";
}
catch(StringIndexOutOfBoundsException err)
{
System.out.println("Invalid Input");
return "<empty>";
}
}
private int numOfOperation(String input)
{
int toReturn = 0;
for (int i = 0; i < input.length(); i++)
{
if(input.charAt(i) == '+' || input.charAt(i) == '/' || input.charAt(i) == '*' || (input.indexOf('-') != -1 && input.charAt(input.indexOf('-') + 1) == ' '))//gets rid of posibility of negatives
{
toReturn++;
}
}
return toReturn;
}
}