Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

Need help in code

  Asked By: Lewis    Date: Feb 01    Category: Java    Views: 740
  

I have the following program, whcih is a calculator, it works brackets too, but
one has to insert a space. Now i did exceptions and i am having an error saying
throwable required. Can anyone help?

Also I would like to add to the program, that when a user enters a letter
instead of a number for example " 22 + a - 3 " , it throws an exception saying
"Only numbers can be inputted!"

Thanking you in advance for any help you give me and also for your time!
import java.io.*;
import java.util.*;

public class fvcalculator {

private static String sEquation ="";
final private static int EXIT_OPTION = -1;


//==============================================================================\
==
// Read user input

//==============================================================================\
==
public static String readText(String message){
BufferedReader input;
String text = "";
try{
System.out.print(message);
input = new BufferedReader(new InputStreamReader(System.in));
text = input.readLine();
}
catch(IOException ioe){
System.out.println("An exception was thrown while reading input from
user.");
}
return text;
}

//==============================================================================\
==



//==============================================================================\
==
// Grouping method - brackets are worked first

//==============================================================================\
==
public static String calc(String input){

int open;
int close;
StringBuffer modifier = new StringBuffer(input);

while((open = input.lastIndexOf("(")) != -1){
close = input.indexOf(")", open);
String subString = input.substring(open + 1, close);
String answer = calculation(parse(subString));
modifier.replace(open, close + 1, answer);
input = modifier.toString();
}

input = calculation(parse(input));

return input;
}

//==============================================================================\
==



//==============================================================================\
==
// Converting equation inputted by user to Vector

//==============================================================================\
==
public static Vector parse(String sEquation){
Vector ParsedsEquation = new Vector ();
String [] temp = sEquation.split ("\\s");

for (int i=0; i<temp.length; i++)
ParsedsEquation.addElement (temp[i]);

return ParsedsEquation;
}

//==============================================================================\
==



//==============================================================================\
==
// Displays answer on the screen

//==============================================================================\
==
public static void printResult(){
System.out.print("\n\nAnswer of " +sEquation + " is: ");
System.out.println(calc(sEquation));
}

//==============================================================================\
==


//==============================================================================\
==
// Array of Operands + Calculation

//==============================================================================\
==
public static String calculation (Vector ParsedsEquation){
char [] operator = {'/','*','+','-'};

for (int i=0; i<operator.length; i++){
while (ParsedsEquation.contains (String.valueOf (operator[i])) !=
false){
int a = ParsedsEquation.indexOf("" +operator[i]);
if (a!=-1){
String answer = computation (""
+ParsedsEquation.get(a-1),operator[i],
"" + ParsedsEquation.get(a+1));
ParsedsEquation.removeElementAt(a-1);
ParsedsEquation.removeElementAt(a-1);
ParsedsEquation.removeElementAt(a-1);
ParsedsEquation.add(a-1, answer);
}
}
}

String result = "";

for (int i=0; i<ParsedsEquation.size();i++)
result = result + ParsedsEquation.elementAt(i);

return result;
}

//==============================================================================\
==



//==============================================================================\
==
// Computation - for operators

//==============================================================================\
==
public static String computation (String a, char op, String b)throws
Calculator Exception{
double firstOperand = 0;
double secondOperand = 0;

try{
firstOperand = Double.parseDouble(a);
}

catch(NumberFormatException nfe){
throw new CalculatorException("The left operand "+a+"cannot be converted into
double");
}

try{
secondOperand = Double.parseDouble (b);
}

catch(NumberFormatException nfe){
throw new CalculatorException("The left operand "+b+"cannot be converted into
double");
}

double result = 0;

switch (op){
case '+':
if (firstOperand/2 + secondOperand/2 >= Double.MAX_VALUE/2)
throw new Calculator Exception("Cannot compute: "+a+" +
"+b+"because of overflow");
else
result = firstOperand + secondOperand;
break;

case '-':
if (firstOperand/2 - secondOperand/2 <= Double.MIN_VALUE/2)
throw new Calculator Exception("Cannot compute: "+a+" -
"+b+"because of overflow");
else
result = firstOperand - secondOperand;
break;

case '*':
if (firstOperand/2 * secondOperand/2 >= Double.MAX_VALUE/2)
throw new Calculator Exception("Cannot compute: "+a+" *
"+b+"because of overflow");
else
result = firstOperand * secondOperand;
break;

case '/':

result = firstOperand / secondOperand;
break;
default:
throw new CalculatorException ("This character'"+op'" is not a
recognized operator!");
}
return String.valueOf(result);
}

//==============================================================================\
==



//==============================================================================\
==
// Main Method - user is asked to enter the mathematical problem using a
space
// between each character inserted. Also the user has the
options
// of continuing using the calculator or exiting the program.
// User has to enter the sEquation using a space. Also
brackets
// must be of the type '(' or ')'

//==============================================================================\
==
public static void main (String args[]){

System.out.println ("*************************");
System.out.println ("\tCALCULATOR ");
System.out.println ("*************************");
sEquation = readText("\nPlease enter the mathematical calculation using
a SPACE:\n ");
printResult();
System.out.println ("-------------------------");

int selectedOption = EXIT_OPTION;
do{
String[] calculatorMenu = {"Continue using the Calculator"};

switch (selectedOption = displayMenu(calculatorMenu, "\t CALCULATOR
MENU")){
case 1:
sEquation = readText("\nPlease enter the mathematical
calculation using a SPACE:\n ");
printResult();
break;
}
}while ( selectedOption!=EXIT_OPTION );

System.out.println("Goodbye...");
}

//==============================================================================\
==


//==============================================================================\
==
// Display Calculator Menu each time the user continues to use the
calculator

//==============================================================================\
==
public static int displayMenu(String[] options, String calculatorMenu){
int selectedOption = EXIT_OPTION;
int selectionSize = options.length;

do{
System.out.println("\n\n\n\n-----------------------------------");
System.out.println(calculatorMenu);
System.out.println("-----------------------------------\n");

for (int i = 0 ; i < selectionSize; i++)
System.out.println((i+1)+"\t"+ options[i]);

System.out.println((selectionSize+1)+"\tExit");
System.out.println("-----------------------------------\n");
try
{
selectedOption = Integer.parseInt(readText("Enter your
selection: "));
}
catch(Exception e){}
}while( !(selectedOption>0 && selectedOption<=selectionSize+1) );

return ((selectedOption==selectionSize+1)?EXIT_OPTION:selectedOption);
}

//==============================================================================\
==

}// end of class

Share: 

 

2 Answers Found

 
Answer #1    Answered By: Dirck Jansen     Answered On: Feb 01

1. you have to make the CalculatorException class.

public class CalculatorException extends exception  {
public CalculatorException() {
super();
}

public CalculatorException(String errorMsg) {
super(errorMsg);
}
}

2. To make things easier, add  throws in several methods to
propagate the exception to the method which will catch it.
public static String calc(String input) throws  CalculatorException {
...}
public static String calculation (Vector ParsedsEquation) throws
CalculatorException {...}
public static String computation (String a, char op, String b)
throws CalculatorException{...}

3. change the printResult() to be able to catch the
CalculatorException

public static void printResult() {
try {
System.out.print("\n\nAnswer of " +sEquation + " is: ");
System.out.println(calc(sEquation));
} catch (CalculatorException ce) {
System.out.println(ce.getMessage());
}
}

4. To throws an exception saying "Only numbers  can be inputted!",
maybe you can check the String with Character.isDigit() method.
eg.

String s = "1234ga";
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (Character.isDigit(c)) {
System.out.println("Digit");
} else {
System.out.println("Non-digit");
}
}

Where to validate it, try to figure it out.

 
Answer #2    Answered By: Calais Bernard     Answered On: Feb 01

1. you have to make the CalculatorException class.

public class CalculatorException extends exception  {
public CalculatorException() {
super();
}

public CalculatorException(String errorMsg) {
super(errorMsg);
}
}

2. To make things easier, add  throws in several methods to
propagate the exception to the method which will catch it.
public static String calc(String input) throws  CalculatorException {
...}
public static String calculation (Vector ParsedsEquation) throws
CalculatorException {...}
public static String computation (String a, char op, String b)
throws CalculatorException{...}

3. change the printResult() to be able to catch the
CalculatorException

public static void printResult() {
try {
System.out.print("\n\nAnswer of " +sEquation + " is: ");
System.out.println(calc(sEquation));
} catch (CalculatorException ce) {
System.out.println(ce.getMessage());
}
}

4. To throws an exception saying "Only numbers  can be inputted!",
maybe you can check the String with Character.isDigit() method.
eg.

String s = "1234ga";
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (Character.isDigit(c)) {
System.out.println("Digit");
} else {
System.out.println("Non-digit");
}
}

Where to validate it, try to figure it out.

 
Didn't find what you were looking for? Find more on Need help in code Or get search suggestion and latest updates.




Tagged: