Java USE ONLY 1 CLASS and name it Postfix. Read a line from System.in representi
ID: 3670791 • Letter: J
Question
Java
USE ONLY 1 CLASS and name it Postfix.
Read a line from System.in representing a postfix expression. Evaluate the expression and print out the numeric result, or Error if the expression is invalid. Use double for all numeric types. DO NOT PRINT ANYTHING ELSE. Exit the program when the user enters a blank line. All symbols will be separated by spaces. Process the input with a loop like so:
Scanner input = new Scanner(System.in);
String line = input.nextLine();
Scanner lineScanner = new Scanner(line);
while(lineScanner.hasNext())
{
if(lineScanner.hasNextDouble())
{
double d = lineScanner.nextDouble();
}
else
{
String operator = lineScanner.next();
}
}
Explanation / Answer
import java.util.Scanner;
/**
* @author Srinivas Palli
*
*/
public class EvaluatePostfixExp {
/**
* @param args
*/
public static void main(String[] args) {
try {
Scanner input = new Scanner(System.in);
System.out.print("Enter the PostFix Expression:");
String line = input.nextLine();
double d[] = new double[2];
int i = 0;
String operator = "";
if (line.equals(""))
System.exit(0);
Scanner lineScanner = new Scanner(line);
while (lineScanner.hasNext()) {
if (lineScanner.hasNextDouble()) {
d[i++] = lineScanner.nextDouble();
} else {
operator = lineScanner.next();
}
}
if (operator == "" || (i != 1)) {
System.out.println("Invalid Expression");
} else {
System.out.println("Result=" + calculate(d[0], d[1], operator));
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
/**
* evaluate the expression
*
* @param x
* @param y
* @param ch
* @return
*/
public static double calculate(double x, double y, String ch) {
double r;
switch (ch) {
case "+":
r = x + y;
break;
case "-":
r = y - x;
break;
case "*":
r = x * y;
break;
case "/":
r = y / x;
break;
default:
r = 0;
}
return r;
}
}
OUTPUT:
Enter the PostFix Expression:4 5 +
Result=9.0
Enter the PostFix Expression:
Enter the PostFix Expression:45
Invalid Expression
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.