SlideShare a Scribd company logo
1 of 6
below is some of the work i began on LispEvaluate on java. but i'm having a hard time figuring
out the rest of the work i need to do. please help me
package lisp;
import java.util.Scanner;
import stack.*;
/**
* The lispCalculate method takes a valid arithmetic
* Lisp expression and evaluates it to calculate the numeric
* output. This code must be provided by you, and will
* make use of stacks.
*
*/
public class LispEvaluate {
/**
* Sets up a loop that treats entered user inputs from the console as Lisp
* expressions, then computes and prints their values. Behavior for badly
* formatted Lisp expressions is not defined, but will likely cause the code
* to crash or otherwise misbehave.
*
* @param args Ignored
*/
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
String input = "";
while(true) {
System.out.print("Enter a Lisp expression or use "q" or "quit" to exit the program: ");
input = console.nextLine();
if(input.equals("q") || input.equals("quit")) break; // Exit the loop
System.out.println("Evaluates to: " + lispCalculate(input));
}
System.out.println("Goodbye");
console.close();
}
/**
* Given a String containing a valid Lisp expression using only
* the operators +, -, /, and *, evaluate the expression and
* return the result.
*
* NOTE: You are NOT allowed to use arrays or ArrayLists. Your algorithm(s)
* should be based on stacks.
*
* @param lispExpression Valid arithmetic Lisp expression.
* @return Numeric result of evaluating the Lisp expression.
*/
public static double lispCalculate(String lispExpression) {
String spacedOut = addSpaces(lispExpression); // Adds extra white space around parentheses
String postfixSpaced = prefixToPostfix(spacedOut); // Converts spaced prefix Lisp expression to
spaced postfix Lisp expression
return calculateSpacedPostfix(postfixSpaced); // Calculates the numeric result from processing
the spaced postfix Lisp expression
}
///// You MUST provide complete and correctly formatted Javadoc comments to all methods
below this point /////
private static String addSpaces(String lispExpression) {
String result = "";
for(int i = 0; i < lispExpression.length(); i++) {
char c = lispExpression.charAt(i);
switch(c) {
case '(':
result += " ( "; // put spaces around (
break;
//more
default:
result += c;
}
}
return result;
}
private static String prefixToPostfix(String spacedOut) {
StackInterface<String> operators = new LinkedStack<>();
String result = "";
Scanner scan = new Scanner(spacedOut);
while(scan.hasNext()) {
String token = scan.next();
switch(token) {
case "+": case "-": case "/": case "*":
operators.push(token);
break;
case "(":
// MORE? WHAT TO DO HERE?
break;
case ")":
result += " " + operators.pop() + " ) ";
break;
default:
result += " " + token + " ";
}
}
scan.close();
return result;
}
private static double calculateSpacedPostfix(String postfixSpaced) {
Scanner scan = new Scanner(postfixSpaced);
StackInterface<Double> operands = new LinkedStack<>();
while(scan.hasNext()) {
String token = scan.next();
switch(token) {
case "+":
//TODO
break;
case "(":
break;
case ")":
//ANYTHING HERE
break;
default:
double value = Double.parseDouble(token);
operands.push(value); // Put each operand on the stack
}
}
scan.close();
return 0;
}
}
below is some of the work i began on LispEvaluate on java- but i'm hav.docx

More Related Content

Similar to below is some of the work i began on LispEvaluate on java- but i'm hav.docx

java write a program to evaluate the postfix expressionthe program.pdf
java write a program to evaluate the postfix expressionthe program.pdfjava write a program to evaluate the postfix expressionthe program.pdf
java write a program to evaluate the postfix expressionthe program.pdf
arjuntelecom26
 
C++ code, please help! RESPOND W COMPLETED CODE PLEASE, am using V.pdf
C++ code, please help! RESPOND W COMPLETED CODE PLEASE,  am using V.pdfC++ code, please help! RESPOND W COMPLETED CODE PLEASE,  am using V.pdf
C++ code, please help! RESPOND W COMPLETED CODE PLEASE, am using V.pdf
rahulfancycorner21
 
The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)
jeffz
 
COMP360 Assembler Write an assembler that reads the source code of an.pdf
COMP360 Assembler Write an assembler that reads the source code of an.pdfCOMP360 Assembler Write an assembler that reads the source code of an.pdf
COMP360 Assembler Write an assembler that reads the source code of an.pdf
fazalenterprises
 
ObjectivesMore practice with recursion.Practice writing some tem.docx
ObjectivesMore practice with recursion.Practice writing some tem.docxObjectivesMore practice with recursion.Practice writing some tem.docx
ObjectivesMore practice with recursion.Practice writing some tem.docx
vannagoforth
 
Unit 4
Unit 4Unit 4
Unit 4
siddr
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
Todor Kolev
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
Todor Kolev
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
Todor Kolev
 

Similar to below is some of the work i began on LispEvaluate on java- but i'm hav.docx (20)

ES6: The Awesome Parts
ES6: The Awesome PartsES6: The Awesome Parts
ES6: The Awesome Parts
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchained
 
Exploit techniques - a quick review
Exploit techniques - a quick reviewExploit techniques - a quick review
Exploit techniques - a quick review
 
ECMAScript 6 Review
ECMAScript 6 ReviewECMAScript 6 Review
ECMAScript 6 Review
 
JavaScript, Beyond the Curly Braces
JavaScript, Beyond the Curly BracesJavaScript, Beyond the Curly Braces
JavaScript, Beyond the Curly Braces
 
RxJS Operators - Real World Use Cases - AngularMix
RxJS Operators - Real World Use Cases - AngularMixRxJS Operators - Real World Use Cases - AngularMix
RxJS Operators - Real World Use Cases - AngularMix
 
java write a program to evaluate the postfix expressionthe program.pdf
java write a program to evaluate the postfix expressionthe program.pdfjava write a program to evaluate the postfix expressionthe program.pdf
java write a program to evaluate the postfix expressionthe program.pdf
 
Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
 
Modern JS with ES6
Modern JS with ES6Modern JS with ES6
Modern JS with ES6
 
C++ code, please help! RESPOND W COMPLETED CODE PLEASE, am using V.pdf
C++ code, please help! RESPOND W COMPLETED CODE PLEASE,  am using V.pdfC++ code, please help! RESPOND W COMPLETED CODE PLEASE,  am using V.pdf
C++ code, please help! RESPOND W COMPLETED CODE PLEASE, am using V.pdf
 
The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)
 
JavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programmingJavaOne 2016 - Learn Lambda and functional programming
JavaOne 2016 - Learn Lambda and functional programming
 
COMP360 Assembler Write an assembler that reads the source code of an.pdf
COMP360 Assembler Write an assembler that reads the source code of an.pdfCOMP360 Assembler Write an assembler that reads the source code of an.pdf
COMP360 Assembler Write an assembler that reads the source code of an.pdf
 
ObjectivesMore practice with recursion.Practice writing some tem.docx
ObjectivesMore practice with recursion.Practice writing some tem.docxObjectivesMore practice with recursion.Practice writing some tem.docx
ObjectivesMore practice with recursion.Practice writing some tem.docx
 
Checking Oracle VM VirtualBox. Part 1
Checking Oracle VM VirtualBox. Part 1Checking Oracle VM VirtualBox. Part 1
Checking Oracle VM VirtualBox. Part 1
 
[2012 CodeEngn Conference 06] pwn3r - Secuinside 2012 CTF 예선 문제풀이
[2012 CodeEngn Conference 06] pwn3r - Secuinside 2012 CTF 예선 문제풀이[2012 CodeEngn Conference 06] pwn3r - Secuinside 2012 CTF 예선 문제풀이
[2012 CodeEngn Conference 06] pwn3r - Secuinside 2012 CTF 예선 문제풀이
 
Unit 4
Unit 4Unit 4
Unit 4
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
 

More from RichardjOZTerryp

C++ Linux Need help with lab assignment- Instructions and code is post.docx
C++ Linux Need help with lab assignment- Instructions and code is post.docxC++ Linux Need help with lab assignment- Instructions and code is post.docx
C++ Linux Need help with lab assignment- Instructions and code is post.docx
RichardjOZTerryp
 

More from RichardjOZTerryp (20)

c- Explain several methods for how zoonotic disease-causing microbes c.docx
c- Explain several methods for how zoonotic disease-causing microbes c.docxc- Explain several methods for how zoonotic disease-causing microbes c.docx
c- Explain several methods for how zoonotic disease-causing microbes c.docx
 
C++ Linux Need help with lab assignment- Instructions and code is post.docx
C++ Linux Need help with lab assignment- Instructions and code is post.docxC++ Linux Need help with lab assignment- Instructions and code is post.docx
C++ Linux Need help with lab assignment- Instructions and code is post.docx
 
C++ 5-6-2 Basic derived class member override Define a member function.docx
C++ 5-6-2 Basic derived class member override Define a member function.docxC++ 5-6-2 Basic derived class member override Define a member function.docx
C++ 5-6-2 Basic derived class member override Define a member function.docx
 
By now everyone has heard news reports about balloons in the sky- Were.docx
By now everyone has heard news reports about balloons in the sky- Were.docxBy now everyone has heard news reports about balloons in the sky- Were.docx
By now everyone has heard news reports about balloons in the sky- Were.docx
 
Businesses that are overleveraged carry a large amount of debt and are.docx
Businesses that are overleveraged carry a large amount of debt and are.docxBusinesses that are overleveraged carry a large amount of debt and are.docx
Businesses that are overleveraged carry a large amount of debt and are.docx
 
Business requirements refine the Logical design phase from a functiona.docx
Business requirements refine the Logical design phase from a functiona.docxBusiness requirements refine the Logical design phase from a functiona.docx
Business requirements refine the Logical design phase from a functiona.docx
 
Briefly explain the following as applied to database design- What is D.docx
Briefly explain the following as applied to database design- What is D.docxBriefly explain the following as applied to database design- What is D.docx
Briefly explain the following as applied to database design- What is D.docx
 
bottles of wine every day- The daily production in Italy is either 200.docx
bottles of wine every day- The daily production in Italy is either 200.docxbottles of wine every day- The daily production in Italy is either 200.docx
bottles of wine every day- The daily production in Italy is either 200.docx
 
Bones Structure and Function Lab Identify the following structures in.docx
Bones Structure and Function Lab Identify the following structures in.docxBones Structure and Function Lab Identify the following structures in.docx
Bones Structure and Function Lab Identify the following structures in.docx
 
Bone and Structure Lab1-) Identify types of bones based upon their sha.docx
Bone and Structure Lab1-) Identify types of bones based upon their sha.docxBone and Structure Lab1-) Identify types of bones based upon their sha.docx
Bone and Structure Lab1-) Identify types of bones based upon their sha.docx
 
bond issue-What will be the total interest payments over the five-year.docx
bond issue-What will be the total interest payments over the five-year.docxbond issue-What will be the total interest payments over the five-year.docx
bond issue-What will be the total interest payments over the five-year.docx
 
Below is the Tycho crater on the surface of the Moon- The left image p.docx
Below is the Tycho crater on the surface of the Moon- The left image p.docxBelow is the Tycho crater on the surface of the Moon- The left image p.docx
Below is the Tycho crater on the surface of the Moon- The left image p.docx
 
Below b a graph showing alinear regression of Ser genotypes and dorsa.docx
Below b a graph showing alinear regression of  Ser genotypes and dorsa.docxBelow b a graph showing alinear regression of  Ser genotypes and dorsa.docx
Below b a graph showing alinear regression of Ser genotypes and dorsa.docx
 
Below is an impact crater on the surface of the Earth- This is the Met.docx
Below is an impact crater on the surface of the Earth- This is the Met.docxBelow is an impact crater on the surface of the Earth- This is the Met.docx
Below is an impact crater on the surface of the Earth- This is the Met.docx
 
Being a taker can be potentially beneficial because- Select one- A- th.docx
Being a taker can be potentially beneficial because- Select one- A- th.docxBeing a taker can be potentially beneficial because- Select one- A- th.docx
Being a taker can be potentially beneficial because- Select one- A- th.docx
 
Below is an idealized diagram of several oceanic plates and a continen.docx
Below is an idealized diagram of several oceanic plates and a continen.docxBelow is an idealized diagram of several oceanic plates and a continen.docx
Below is an idealized diagram of several oceanic plates and a continen.docx
 
Begin on the left side of the map and trace over 30oN latitude with yo.docx
Begin on the left side of the map and trace over 30oN latitude with yo.docxBegin on the left side of the map and trace over 30oN latitude with yo.docx
Begin on the left side of the map and trace over 30oN latitude with yo.docx
 
Before June production is recorded- the Work in Process inventory acco.docx
Before June production is recorded- the Work in Process inventory acco.docxBefore June production is recorded- the Work in Process inventory acco.docx
Before June production is recorded- the Work in Process inventory acco.docx
 
Because human wants are insatiable and unlimited while available resou.docx
Because human wants are insatiable and unlimited while available resou.docxBecause human wants are insatiable and unlimited while available resou.docx
Because human wants are insatiable and unlimited while available resou.docx
 
Cash budgets are based on cash accounting rather than accrual accounti.docx
Cash budgets are based on cash accounting rather than accrual accounti.docxCash budgets are based on cash accounting rather than accrual accounti.docx
Cash budgets are based on cash accounting rather than accrual accounti.docx
 

Recently uploaded

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Recently uploaded (20)

HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 

below is some of the work i began on LispEvaluate on java- but i'm hav.docx

  • 1. below is some of the work i began on LispEvaluate on java. but i'm having a hard time figuring out the rest of the work i need to do. please help me package lisp; import java.util.Scanner; import stack.*; /** * The lispCalculate method takes a valid arithmetic * Lisp expression and evaluates it to calculate the numeric * output. This code must be provided by you, and will * make use of stacks. * */ public class LispEvaluate { /** * Sets up a loop that treats entered user inputs from the console as Lisp * expressions, then computes and prints their values. Behavior for badly * formatted Lisp expressions is not defined, but will likely cause the code * to crash or otherwise misbehave. * * @param args Ignored */ public static void main(String[] args) { Scanner console = new Scanner(System.in); String input = "";
  • 2. while(true) { System.out.print("Enter a Lisp expression or use "q" or "quit" to exit the program: "); input = console.nextLine(); if(input.equals("q") || input.equals("quit")) break; // Exit the loop System.out.println("Evaluates to: " + lispCalculate(input)); } System.out.println("Goodbye"); console.close(); } /** * Given a String containing a valid Lisp expression using only * the operators +, -, /, and *, evaluate the expression and * return the result. * * NOTE: You are NOT allowed to use arrays or ArrayLists. Your algorithm(s) * should be based on stacks. * * @param lispExpression Valid arithmetic Lisp expression. * @return Numeric result of evaluating the Lisp expression. */ public static double lispCalculate(String lispExpression) { String spacedOut = addSpaces(lispExpression); // Adds extra white space around parentheses String postfixSpaced = prefixToPostfix(spacedOut); // Converts spaced prefix Lisp expression to spaced postfix Lisp expression
  • 3. return calculateSpacedPostfix(postfixSpaced); // Calculates the numeric result from processing the spaced postfix Lisp expression } ///// You MUST provide complete and correctly formatted Javadoc comments to all methods below this point ///// private static String addSpaces(String lispExpression) { String result = ""; for(int i = 0; i < lispExpression.length(); i++) { char c = lispExpression.charAt(i); switch(c) { case '(': result += " ( "; // put spaces around ( break; //more default: result += c; } } return result; } private static String prefixToPostfix(String spacedOut) { StackInterface<String> operators = new LinkedStack<>(); String result = ""; Scanner scan = new Scanner(spacedOut);
  • 4. while(scan.hasNext()) { String token = scan.next(); switch(token) { case "+": case "-": case "/": case "*": operators.push(token); break; case "(": // MORE? WHAT TO DO HERE? break; case ")": result += " " + operators.pop() + " ) "; break; default: result += " " + token + " "; } } scan.close(); return result; } private static double calculateSpacedPostfix(String postfixSpaced) { Scanner scan = new Scanner(postfixSpaced); StackInterface<Double> operands = new LinkedStack<>(); while(scan.hasNext()) {
  • 5. String token = scan.next(); switch(token) { case "+": //TODO break; case "(": break; case ")": //ANYTHING HERE break; default: double value = Double.parseDouble(token); operands.push(value); // Put each operand on the stack } } scan.close(); return 0; } }