FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
Java/Others/StackPostfixNotation.java at master · primary-code-test/Java · GitHub
primary-code-test
Java
Repository navigation
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
Java
/
Others
/
StackPostfixNotation.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
42 lines (36 loc) · 1.14 KB
Breadcrumbs
Java
/
Others
/
StackPostfixNotation.java
Copy path
File metadata and controls
42 lines (36 loc) · 1.14 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
package
Others
;
import
java
.
util
.*;
public
class
StackPostfixNotation
{
public
static
void
main
(
String
[]
args
) {
Scanner
scanner
=
new
Scanner
(
System
.
in
);
String
post
=
scanner
.
nextLine
();
// Takes input with spaces in between eg. "1 21 +"
System
.
out
.
println
(
postfixEvaluate
(
post
));
scanner
.
close
();
}
// Evaluates the given postfix expression string and returns the result.
public
static
int
postfixEvaluate
(
String
exp
) {
Stack
<
Integer
>
s
=
new
Stack
<
Integer
>();
Scanner
tokens
=
new
Scanner
(
exp
);
while
(
tokens
.
hasNext
()) {
if
(
tokens
.
hasNextInt
()) {
s
.
push
(
tokens
.
nextInt
());
// If int then push to stack
}
else
{
// else pop top two values and perform the operation
int
num2
=
s
.
pop
();
int
num1
=
s
.
pop
();
String
op
=
tokens
.
next
();
if
(
op
.
equals
(
"+"
)) {
s
.
push
(
num1
+
num2
);
}
else
if
(
op
.
equals
(
"-"
)) {
s
.
push
(
num1
-
num2
);
}
else
if
(
op
.
equals
(
"*"
)) {
s
.
push
(
num1
*
num2
);
}
else
{
s
.
push
(
num1
/
num2
);
}
// "+", "-", "*", "/"
}
}
tokens
.
close
();
return
s
.
pop
();
}
}
Back
|
FazBrowse Home
|
New Git URL