forked from google/codeu_coding_assessment_2017
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCalculator.java
85 lines (74 loc) · 1.61 KB
/
Calculator.java
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
78
79
80
81
82
83
84
85
import java.util.*;
public class Calculator {
public static void main(String[] args){
Scanner s= new Scanner(System.in);
String one= s.next();
System.out.println(Calcu(one));
}
public static int Calcu(String one) {
int x=0;
x=one.charAt(0)-'0';
char c= '+';
char d= '*';
char e= '/';
char f= '-';
char g= '^';
for (int i=0; i<one.length(); i++) {
int y;
y=one.charAt(i+1)-'0';
/*
if (i==one.charAt(i)) {
x=y;
}
*/
if (i==c) {
x+=y;
}
else if (i==d) {
x*=y;
}
else if (i==e) {
x/=y;
}
else if (i==f) {
x-=y;
}
else if (i==g){
Math.pow(x,y);
}
else {
System.out.print("You typed an error!");
}
}
return x;
}
}
//whenever
//output+=charAt(i+1)
import java.util.*;
public class StringCalc{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = input.nextLine();
calculate(str);
}
public static void calculate(String str){
double finalNum = str.charAt(0) - 48;
for(int i = 1; i< str.length(); i++){
String temp = "" + str.charAt(i);
if(temp.equals("+")){
finalNum = finalNum + (str.charAt(i+1) - 48);
}else if(temp.equals("-")){
finalNum = finalNum -(str.charAt(i+1) - 48);
}else if(temp.equals("*")){
finalNum = finalNum * (str.charAt(i+1) - 48);
}else if(temp.equals("/")){
finalNum = finalNum / (str.charAt(i+1) - 48);
}else if(temp.equals("^")){
finalNum = Math.pow(finalNum, (str.charAt(i+1)-48));
}
}
System.out.printf("%.2f", finalNum);
System.out.println();
}
}