SlideShare a Scribd company logo
1 of 8
Download to read offline
//Tested on Eclipse and both class should be in same package
import java.util.Scanner;
public class P3 {
/*isInteger method implementation
* @param String type
* while parsing if it throw exception then it is not integer
* else it is integer*/
public static Boolean isDouble(String token){
try {
Double.parseDouble(token);
} catch(NumberFormatException e) {
System.out.println("Invalid Operand");
return false;
} catch(NullPointerException e) {
System.out.println("Invalid Operand");
return false;
}
// only got here if we didn't return false
return true;
}
public static String evaluate(String expression) {
// Print expression
System.out.print(expression);
// Declare variables for operands, operator, result, and return value
double operand1=0,operand2 = 0,result=0;
char operator;
Boolean flag=Boolean.FALSE;//for if operators were not listed
String returnString = "";
String token[]=new String[expression.length()];//for storing all token from expression
// Create Scanner object to parse expression
// create a new scanner with the specified String Object
int i=0;
Scanner scanner = new Scanner(expression);
while(scanner.hasNext()){
token[i]=scanner.next();
i++;
}
scanner.close();
// Compute a numerical result for the expression
if(isDouble(token[0])){
operand1=Double.parseDouble(token[0]);
}
if(isDouble(token[2])){
operand2=Double.parseDouble(token[2]);
}
operator=token[1].charAt(0);
if(operand1!=0&&operand2!=0){
switch(operator){
case '+':
result=operand1+operand2;
break;
case '-':
result=operand1-operand2;
break;
case '*':
result=operand1*operand2;
break;
case '/':
result=operand1/operand2;
break;
case '%':
result=operand1%operand2;
break;
case '^':
result=Math.pow(operand1, operand2);
break;
default:
System.out.println("Invalid Operator");
flag=Boolean.TRUE;
break;
}
// Convert numerical result to string
returnString=Double.toString(result);
if(flag){
return null;
}
// Return result
return returnString;
}else{
return null;
}
}
}
/*********Calculator class***************/
import java.util.Scanner;
/*Calculator class start*/
public class Calculator {
public static void main(String args[]){
/*Variable declaration*/
String expression;
/*Scanner object for input*/
Scanner input=new Scanner(System.in);
/*Prompt for expression*/
System.out.println("Please Enter expression");
expression=input.nextLine();
input.close();
/*Calling Evaluate method*/
String result=P3.evaluate(expression);
/*Printing result if it is not null*/
if(result!=null) {
System.out.println(result);
}
}
}
/***************output************/
Please Enter expression
11.22 + 3.456 =
11.22 + 3.456 =14.676
Please Enter expression
5.555 - 32.14 =
5.555 - 32.14 =-26.585
Please Enter expression
25634.8 * .32 =
25634.8 * .32 = 8203.136
Please Enter expression
5 ^ 4 =
5 ^ 4 =625.0
Please Enter expression
Whatever + 2 =
Whatever + 2 =Invalid Operand
Please Enter expression
4.0 - 1.2.3 =
4.0 - 1.2.3 =Invalid Operand
Please Enter expression
1.234 $ 0.5 =
1.234 $ 0.5 =Invalid Operator
Thanks a lot
Solution
//Tested on Eclipse and both class should be in same package
import java.util.Scanner;
public class P3 {
/*isInteger method implementation
* @param String type
* while parsing if it throw exception then it is not integer
* else it is integer*/
public static Boolean isDouble(String token){
try {
Double.parseDouble(token);
} catch(NumberFormatException e) {
System.out.println("Invalid Operand");
return false;
} catch(NullPointerException e) {
System.out.println("Invalid Operand");
return false;
}
// only got here if we didn't return false
return true;
}
public static String evaluate(String expression) {
// Print expression
System.out.print(expression);
// Declare variables for operands, operator, result, and return value
double operand1=0,operand2 = 0,result=0;
char operator;
Boolean flag=Boolean.FALSE;//for if operators were not listed
String returnString = "";
String token[]=new String[expression.length()];//for storing all token from expression
// Create Scanner object to parse expression
// create a new scanner with the specified String Object
int i=0;
Scanner scanner = new Scanner(expression);
while(scanner.hasNext()){
token[i]=scanner.next();
i++;
}
scanner.close();
// Compute a numerical result for the expression
if(isDouble(token[0])){
operand1=Double.parseDouble(token[0]);
}
if(isDouble(token[2])){
operand2=Double.parseDouble(token[2]);
}
operator=token[1].charAt(0);
if(operand1!=0&&operand2!=0){
switch(operator){
case '+':
result=operand1+operand2;
break;
case '-':
result=operand1-operand2;
break;
case '*':
result=operand1*operand2;
break;
case '/':
result=operand1/operand2;
break;
case '%':
result=operand1%operand2;
break;
case '^':
result=Math.pow(operand1, operand2);
break;
default:
System.out.println("Invalid Operator");
flag=Boolean.TRUE;
break;
}
// Convert numerical result to string
returnString=Double.toString(result);
if(flag){
return null;
}
// Return result
return returnString;
}else{
return null;
}
}
}
/*********Calculator class***************/
import java.util.Scanner;
/*Calculator class start*/
public class Calculator {
public static void main(String args[]){
/*Variable declaration*/
String expression;
/*Scanner object for input*/
Scanner input=new Scanner(System.in);
/*Prompt for expression*/
System.out.println("Please Enter expression");
expression=input.nextLine();
input.close();
/*Calling Evaluate method*/
String result=P3.evaluate(expression);
/*Printing result if it is not null*/
if(result!=null) {
System.out.println(result);
}
}
}
/***************output************/
Please Enter expression
11.22 + 3.456 =
11.22 + 3.456 =14.676
Please Enter expression
5.555 - 32.14 =
5.555 - 32.14 =-26.585
Please Enter expression
25634.8 * .32 =
25634.8 * .32 = 8203.136
Please Enter expression
5 ^ 4 =
5 ^ 4 =625.0
Please Enter expression
Whatever + 2 =
Whatever + 2 =Invalid Operand
Please Enter expression
4.0 - 1.2.3 =
4.0 - 1.2.3 =Invalid Operand
Please Enter expression
1.234 $ 0.5 =
1.234 $ 0.5 =Invalid Operator
Thanks a lot

More Related Content

Similar to Tested on Eclipse and both class should be in same packageimport.pdf

java compilerCompiler1.javajava compilerCompiler1.javaimport.docx
java compilerCompiler1.javajava compilerCompiler1.javaimport.docxjava compilerCompiler1.javajava compilerCompiler1.javaimport.docx
java compilerCompiler1.javajava compilerCompiler1.javaimport.docx
priestmanmable
 
Unit Testing Standards - Recommended Best Practices
Unit Testing Standards - Recommended Best PracticesUnit Testing Standards - Recommended Best Practices
Unit Testing Standards - Recommended Best Practices
Vitaliy Kulikov
 
Integration Project Inspection 3
Integration Project Inspection 3Integration Project Inspection 3
Integration Project Inspection 3
Dillon Lee
 

Similar to Tested on Eclipse and both class should be in same packageimport.pdf (19)

java compilerCompiler1.javajava compilerCompiler1.javaimport.docx
java compilerCompiler1.javajava compilerCompiler1.javaimport.docxjava compilerCompiler1.javajava compilerCompiler1.javaimport.docx
java compilerCompiler1.javajava compilerCompiler1.javaimport.docx
 
GeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good TestsGeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good Tests
 
Java API, Exceptions and IO
Java API, Exceptions and IOJava API, Exceptions and IO
Java API, Exceptions and IO
 
Algoritmos sujei
Algoritmos sujeiAlgoritmos sujei
Algoritmos sujei
 
Unit Testing Standards - Recommended Best Practices
Unit Testing Standards - Recommended Best PracticesUnit Testing Standards - Recommended Best Practices
Unit Testing Standards - Recommended Best Practices
 
Problemas secuenciales.
Problemas secuenciales.Problemas secuenciales.
Problemas secuenciales.
 
Problemas secuenciales.
Problemas secuenciales.Problemas secuenciales.
Problemas secuenciales.
 
Problemas secuenciales.
Problemas secuenciales.Problemas secuenciales.
Problemas secuenciales.
 
Problemas secuenciales.
Problemas secuenciales.Problemas secuenciales.
Problemas secuenciales.
 
Problemas secuenciales.
Problemas secuenciales.Problemas secuenciales.
Problemas secuenciales.
 
Enterprise js pratices
Enterprise js praticesEnterprise js pratices
Enterprise js pratices
 
Confitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good TestsConfitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good Tests
 
Integration Project Inspection 3
Integration Project Inspection 3Integration Project Inspection 3
Integration Project Inspection 3
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming Language
 
C++ boot camp part 1/2
C++ boot camp part 1/2C++ boot camp part 1/2
C++ boot camp part 1/2
 
C++ Boot Camp Part 1
C++ Boot Camp Part 1C++ Boot Camp Part 1
C++ Boot Camp Part 1
 
Java 5 Features
Java 5 FeaturesJava 5 Features
Java 5 Features
 
Effective Java - Enum and Annotations
Effective Java - Enum and AnnotationsEffective Java - Enum and Annotations
Effective Java - Enum and Annotations
 
Jdk1.5 Features
Jdk1.5 FeaturesJdk1.5 Features
Jdk1.5 Features
 

More from anuradhasilks

identical is the exact same, this is the top r.pdf
                     identical is the exact same, this is the top r.pdf                     identical is the exact same, this is the top r.pdf
identical is the exact same, this is the top r.pdf
anuradhasilks
 
TriangleU210.javapublic class TriangleU210 {    Declaring inst.pdf
TriangleU210.javapublic class TriangleU210 {    Declaring inst.pdfTriangleU210.javapublic class TriangleU210 {    Declaring inst.pdf
TriangleU210.javapublic class TriangleU210 {    Declaring inst.pdf
anuradhasilks
 
PsychoanalysisPsychoanalysis was founded by Sigmund Freud (1856-19.pdf
PsychoanalysisPsychoanalysis was founded by Sigmund Freud (1856-19.pdfPsychoanalysisPsychoanalysis was founded by Sigmund Freud (1856-19.pdf
PsychoanalysisPsychoanalysis was founded by Sigmund Freud (1856-19.pdf
anuradhasilks
 
Of the variedtypes of IPC, sockets arout and awaythe foremostcommon..pdf
Of the variedtypes of IPC, sockets arout and awaythe foremostcommon..pdfOf the variedtypes of IPC, sockets arout and awaythe foremostcommon..pdf
Of the variedtypes of IPC, sockets arout and awaythe foremostcommon..pdf
anuradhasilks
 

More from anuradhasilks (20)

The Arrhenius Theory of acids and bases The theo.pdf
                     The Arrhenius Theory of acids and bases  The theo.pdf                     The Arrhenius Theory of acids and bases  The theo.pdf
The Arrhenius Theory of acids and bases The theo.pdf
 
oxygen in air (O2) reacts with H2 when it burns .pdf
                     oxygen in air (O2) reacts with H2 when it burns  .pdf                     oxygen in air (O2) reacts with H2 when it burns  .pdf
oxygen in air (O2) reacts with H2 when it burns .pdf
 
x+12=1 x=12 .pdf
                     x+12=1 x=12                                    .pdf                     x+12=1 x=12                                    .pdf
x+12=1 x=12 .pdf
 
most of the hydrogens on the benzene were replace.pdf
                     most of the hydrogens on the benzene were replace.pdf                     most of the hydrogens on the benzene were replace.pdf
most of the hydrogens on the benzene were replace.pdf
 
Li2S Solution Li2S .pdf
                     Li2S  Solution                     Li2S  .pdf                     Li2S  Solution                     Li2S  .pdf
Li2S Solution Li2S .pdf
 
identical is the exact same, this is the top r.pdf
                     identical is the exact same, this is the top r.pdf                     identical is the exact same, this is the top r.pdf
identical is the exact same, this is the top r.pdf
 
This is a nucleophilic substitution reaction that.pdf
                     This is a nucleophilic substitution reaction that.pdf                     This is a nucleophilic substitution reaction that.pdf
This is a nucleophilic substitution reaction that.pdf
 
Sulfur is oxidized and nitrogen is reduced. .pdf
                     Sulfur is oxidized and nitrogen is reduced.      .pdf                     Sulfur is oxidized and nitrogen is reduced.      .pdf
Sulfur is oxidized and nitrogen is reduced. .pdf
 
TriangleU210.javapublic class TriangleU210 {    Declaring inst.pdf
TriangleU210.javapublic class TriangleU210 {    Declaring inst.pdfTriangleU210.javapublic class TriangleU210 {    Declaring inst.pdf
TriangleU210.javapublic class TriangleU210 {    Declaring inst.pdf
 
There is some data missing in the problem.The composition of the m.pdf
There is some data missing in the problem.The composition of the m.pdfThere is some data missing in the problem.The composition of the m.pdf
There is some data missing in the problem.The composition of the m.pdf
 
at beginning flask has only NaOH pH = 14 + log [N.pdf
                     at beginning flask has only NaOH pH = 14 + log [N.pdf                     at beginning flask has only NaOH pH = 14 + log [N.pdf
at beginning flask has only NaOH pH = 14 + log [N.pdf
 
take log on both sides1n lna = ln las a--0.pdf
take log on both sides1n lna = ln las a--0.pdftake log on both sides1n lna = ln las a--0.pdf
take log on both sides1n lna = ln las a--0.pdf
 
Solution A person in perfect health has a utility score of 1.0U.pdf
Solution A person in perfect health has a utility score of 1.0U.pdfSolution A person in perfect health has a utility score of 1.0U.pdf
Solution A person in perfect health has a utility score of 1.0U.pdf
 
Resurgent infection is suggesting that it is viral infection by meas.pdf
Resurgent infection is suggesting that it is viral infection by meas.pdfResurgent infection is suggesting that it is viral infection by meas.pdf
Resurgent infection is suggesting that it is viral infection by meas.pdf
 
There are only two functional groups in the molec.pdf
                     There are only two functional groups in the molec.pdf                     There are only two functional groups in the molec.pdf
There are only two functional groups in the molec.pdf
 
PsychoanalysisPsychoanalysis was founded by Sigmund Freud (1856-19.pdf
PsychoanalysisPsychoanalysis was founded by Sigmund Freud (1856-19.pdfPsychoanalysisPsychoanalysis was founded by Sigmund Freud (1856-19.pdf
PsychoanalysisPsychoanalysis was founded by Sigmund Freud (1856-19.pdf
 
Product of Cyclopentane + H2O(H+) gives No Reaction.It will simply F.pdf
Product of Cyclopentane + H2O(H+) gives No Reaction.It will simply F.pdfProduct of Cyclopentane + H2O(H+) gives No Reaction.It will simply F.pdf
Product of Cyclopentane + H2O(H+) gives No Reaction.It will simply F.pdf
 
Of the variedtypes of IPC, sockets arout and awaythe foremostcommon..pdf
Of the variedtypes of IPC, sockets arout and awaythe foremostcommon..pdfOf the variedtypes of IPC, sockets arout and awaythe foremostcommon..pdf
Of the variedtypes of IPC, sockets arout and awaythe foremostcommon..pdf
 
C2O2 is a bidendate ligand &Cl - is a mono dendat.pdf
                     C2O2 is a bidendate ligand &Cl - is a mono dendat.pdf                     C2O2 is a bidendate ligand &Cl - is a mono dendat.pdf
C2O2 is a bidendate ligand &Cl - is a mono dendat.pdf
 
Insulin receptor signaling is represented by figure DEffect of hyp.pdf
Insulin receptor signaling is represented by figure DEffect of hyp.pdfInsulin receptor signaling is represented by figure DEffect of hyp.pdf
Insulin receptor signaling is represented by figure DEffect of hyp.pdf
 

Recently uploaded

會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
中 央社
 
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
中 央社
 
SPLICE Working Group: Reusable Code Examples
SPLICE Working Group:Reusable Code ExamplesSPLICE Working Group:Reusable Code Examples
SPLICE Working Group: Reusable Code Examples
Peter Brusilovsky
 
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes GuàrdiaPersonalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
EADTU
 

Recently uploaded (20)

OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
e-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi Rajagopale-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi Rajagopal
 
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjjStl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
 
ANTI PARKISON DRUGS.pptx
ANTI         PARKISON          DRUGS.pptxANTI         PARKISON          DRUGS.pptx
ANTI PARKISON DRUGS.pptx
 
VAMOS CUIDAR DO NOSSO PLANETA! .
VAMOS CUIDAR DO NOSSO PLANETA!                    .VAMOS CUIDAR DO NOSSO PLANETA!                    .
VAMOS CUIDAR DO NOSSO PLANETA! .
 
How to Manage Website in Odoo 17 Studio App.pptx
How to Manage Website in Odoo 17 Studio App.pptxHow to Manage Website in Odoo 17 Studio App.pptx
How to Manage Website in Odoo 17 Studio App.pptx
 
ESSENTIAL of (CS/IT/IS) class 07 (Networks)
ESSENTIAL of (CS/IT/IS) class 07 (Networks)ESSENTIAL of (CS/IT/IS) class 07 (Networks)
ESSENTIAL of (CS/IT/IS) class 07 (Networks)
 
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
 
diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....
 
Major project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategiesMajor project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategies
 
SPLICE Working Group: Reusable Code Examples
SPLICE Working Group:Reusable Code ExamplesSPLICE Working Group:Reusable Code Examples
SPLICE Working Group: Reusable Code Examples
 
Graduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptxGraduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptx
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
 
MOOD STABLIZERS DRUGS.pptx
MOOD     STABLIZERS           DRUGS.pptxMOOD     STABLIZERS           DRUGS.pptx
MOOD STABLIZERS DRUGS.pptx
 
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes GuàrdiaPersonalisation of Education by AI and Big Data - Lourdes Guàrdia
Personalisation of Education by AI and Big Data - Lourdes Guàrdia
 
PSYPACT- Practicing Over State Lines May 2024.pptx
PSYPACT- Practicing Over State Lines May 2024.pptxPSYPACT- Practicing Over State Lines May 2024.pptx
PSYPACT- Practicing Over State Lines May 2024.pptx
 
Đề tieng anh thpt 2024 danh cho cac ban hoc sinh
Đề tieng anh thpt 2024 danh cho cac ban hoc sinhĐề tieng anh thpt 2024 danh cho cac ban hoc sinh
Đề tieng anh thpt 2024 danh cho cac ban hoc sinh
 
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
 
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
 

Tested on Eclipse and both class should be in same packageimport.pdf

  • 1. //Tested on Eclipse and both class should be in same package import java.util.Scanner; public class P3 { /*isInteger method implementation * @param String type * while parsing if it throw exception then it is not integer * else it is integer*/ public static Boolean isDouble(String token){ try { Double.parseDouble(token); } catch(NumberFormatException e) { System.out.println("Invalid Operand"); return false; } catch(NullPointerException e) { System.out.println("Invalid Operand"); return false; } // only got here if we didn't return false return true; } public static String evaluate(String expression) { // Print expression System.out.print(expression); // Declare variables for operands, operator, result, and return value double operand1=0,operand2 = 0,result=0; char operator; Boolean flag=Boolean.FALSE;//for if operators were not listed String returnString = ""; String token[]=new String[expression.length()];//for storing all token from expression // Create Scanner object to parse expression // create a new scanner with the specified String Object int i=0; Scanner scanner = new Scanner(expression); while(scanner.hasNext()){ token[i]=scanner.next();
  • 2. i++; } scanner.close(); // Compute a numerical result for the expression if(isDouble(token[0])){ operand1=Double.parseDouble(token[0]); } if(isDouble(token[2])){ operand2=Double.parseDouble(token[2]); } operator=token[1].charAt(0); if(operand1!=0&&operand2!=0){ switch(operator){ case '+': result=operand1+operand2; break; case '-': result=operand1-operand2; break; case '*': result=operand1*operand2; break; case '/': result=operand1/operand2; break; case '%': result=operand1%operand2; break; case '^': result=Math.pow(operand1, operand2); break; default: System.out.println("Invalid Operator"); flag=Boolean.TRUE; break; }
  • 3. // Convert numerical result to string returnString=Double.toString(result); if(flag){ return null; } // Return result return returnString; }else{ return null; } } } /*********Calculator class***************/ import java.util.Scanner; /*Calculator class start*/ public class Calculator { public static void main(String args[]){ /*Variable declaration*/ String expression; /*Scanner object for input*/ Scanner input=new Scanner(System.in); /*Prompt for expression*/ System.out.println("Please Enter expression"); expression=input.nextLine(); input.close(); /*Calling Evaluate method*/ String result=P3.evaluate(expression); /*Printing result if it is not null*/ if(result!=null) { System.out.println(result); } } }
  • 4. /***************output************/ Please Enter expression 11.22 + 3.456 = 11.22 + 3.456 =14.676 Please Enter expression 5.555 - 32.14 = 5.555 - 32.14 =-26.585 Please Enter expression 25634.8 * .32 = 25634.8 * .32 = 8203.136 Please Enter expression 5 ^ 4 = 5 ^ 4 =625.0 Please Enter expression Whatever + 2 = Whatever + 2 =Invalid Operand Please Enter expression 4.0 - 1.2.3 = 4.0 - 1.2.3 =Invalid Operand Please Enter expression 1.234 $ 0.5 = 1.234 $ 0.5 =Invalid Operator Thanks a lot Solution //Tested on Eclipse and both class should be in same package import java.util.Scanner; public class P3 { /*isInteger method implementation * @param String type * while parsing if it throw exception then it is not integer * else it is integer*/ public static Boolean isDouble(String token){ try { Double.parseDouble(token);
  • 5. } catch(NumberFormatException e) { System.out.println("Invalid Operand"); return false; } catch(NullPointerException e) { System.out.println("Invalid Operand"); return false; } // only got here if we didn't return false return true; } public static String evaluate(String expression) { // Print expression System.out.print(expression); // Declare variables for operands, operator, result, and return value double operand1=0,operand2 = 0,result=0; char operator; Boolean flag=Boolean.FALSE;//for if operators were not listed String returnString = ""; String token[]=new String[expression.length()];//for storing all token from expression // Create Scanner object to parse expression // create a new scanner with the specified String Object int i=0; Scanner scanner = new Scanner(expression); while(scanner.hasNext()){ token[i]=scanner.next(); i++; } scanner.close(); // Compute a numerical result for the expression if(isDouble(token[0])){ operand1=Double.parseDouble(token[0]); } if(isDouble(token[2])){ operand2=Double.parseDouble(token[2]); } operator=token[1].charAt(0);
  • 6. if(operand1!=0&&operand2!=0){ switch(operator){ case '+': result=operand1+operand2; break; case '-': result=operand1-operand2; break; case '*': result=operand1*operand2; break; case '/': result=operand1/operand2; break; case '%': result=operand1%operand2; break; case '^': result=Math.pow(operand1, operand2); break; default: System.out.println("Invalid Operator"); flag=Boolean.TRUE; break; } // Convert numerical result to string returnString=Double.toString(result); if(flag){ return null; } // Return result return returnString; }else{ return null; }
  • 7. } } /*********Calculator class***************/ import java.util.Scanner; /*Calculator class start*/ public class Calculator { public static void main(String args[]){ /*Variable declaration*/ String expression; /*Scanner object for input*/ Scanner input=new Scanner(System.in); /*Prompt for expression*/ System.out.println("Please Enter expression"); expression=input.nextLine(); input.close(); /*Calling Evaluate method*/ String result=P3.evaluate(expression); /*Printing result if it is not null*/ if(result!=null) { System.out.println(result); } } } /***************output************/ Please Enter expression 11.22 + 3.456 = 11.22 + 3.456 =14.676 Please Enter expression 5.555 - 32.14 = 5.555 - 32.14 =-26.585 Please Enter expression 25634.8 * .32 = 25634.8 * .32 = 8203.136 Please Enter expression
  • 8. 5 ^ 4 = 5 ^ 4 =625.0 Please Enter expression Whatever + 2 = Whatever + 2 =Invalid Operand Please Enter expression 4.0 - 1.2.3 = 4.0 - 1.2.3 =Invalid Operand Please Enter expression 1.234 $ 0.5 = 1.234 $ 0.5 =Invalid Operator Thanks a lot