Question

In Java. Please use the provided code

Required Items: 1. Create a new class and name it HwO6Source, and it contains the main method. In Hw06Source class, define an3. In CalculateHelper class implement exception handling in the process method to catch the three different error happened in

Homework 5 Code:

public class Hw05Source {
public static void main(String[] args)
{
String[] equations ={"Divide 100.0 50.0",
"Add 25.0 92.0", "Subtract 225.0 17.0",
"Multiply 11.0 3.0"};
CalculateHelper helper= new CalculateHelper();
for (int i = 0;i {
helper.process(equations[i]);
helper.calculate();
System.out.println(helper);
}
}
}

//==========================================

public class MathEquation {
double leftValue;
double rightValue;
double result;
char opCode='a';

private MathEquation(){
}

public MathEquation(char opCode) {
this();
this.opCode = opCode;
}
public MathEquation(char opCode,double leftVal,double rightValue){
this(opCode);
this.leftValue=leftVal;
this.rightValue=rightValue;
}

public double getResult() {
return result;
}

void execute(int leftValue,int rightValue){
this.leftValue=leftValue;
this.rightValue=rightValue;
execute();
result=(int)result;
}
void execute(double leftValue,double rightValue){
this.leftValue=leftValue;
this.rightValue=rightValue;
execute();
}
void execute(){
switch (opCode){
case 'a':
result=leftValue+rightValue;
break;
case 's':
result=leftValue-rightValue;
break;
case 'm':
result=leftValue*rightValue;
break;
case 'd':
if(rightValue==0){
System.out.println("Error: right Value for division can be not zero!!!");
result = 0.0d;
break;
}
result=leftValue/rightValue;
break;
default:
System.out.println("Error: Invalid Operation Code");
result = 0.0d;
break;
}
}
}

//============================================

public abstract class CalculateBase {
private double leftValue;
private double rightValue;
private double result;

public double getLeftValue() {
return leftValue;
}

public void setLeftValue(double leftValue) {
this.leftValue = leftValue;
}

public double getRightValue() {
return rightValue;
}

public void setRightValue(double rightValue) {
this.rightValue = rightValue;
}

public double getResult() {
return result;
}

public void setResult(double result) {
this.result = result;
}

public CalculateBase() {
}

public CalculateBase(double leftValue, double rightValue) {
this();
this.leftValue = leftValue;
this.rightValue = rightValue;
}

public abstract void calculate();
}

//====================================

public class Adder extends CalculateBase{
public Adder() {
}

public Adder(double leftValue, double rightValue) {
super(leftValue, rightValue);
}

@Override
public void calculate() {
double value=getLeftValue()+getRightValue();
setResult(value);
}
}

//=====================================

public class Multiplier extends CalculateBase{
public Multiplier() {
}

public Multiplier(double leftValue, double rightValue) {
super(leftValue, rightValue);
}

@Override
public void calculate() {
double value=getLeftValue()*getRightValue();
setResult(value);
}
}

//===========================================

public class Subtractor extends CalculateBase {

public Subtractor() {
}
public Subtractor(double leftValue, double rightValue) {
super(leftValue, rightValue);
}
@Override
public void calculate() {
double value=getLeftValue()-getRightValue();
setResult(value);
}
}

//==============================

public class Divider extends CalculateBase {
public Divider() {
}

public Divider(double leftValue, double rightValue) {
super(leftValue, rightValue);
}

@Override
public void calculate() {
if(getRightValue()==0){
setResult(0);
return;
}
double value=getLeftValue()/getRightValue();
setResult(value);
}
}

//===========================================

public enum MathCommand {
Add, Subtract, Multiply, Divide;
}

//==========================================

public class CalculateHelper extends CalculateBase{
private double leftValue;
private double rightValue;
private double result;
MathCommand command;
public CalculateHelper()
{
leftValue =0;
rightValue=0;
result =0;
command = null;
}
public void process(String equation)
{
String[] tokens = equation.split(" ");
leftValue = Double.parseDouble(tokens[1]);
rightValue = Double.parseDouble(tokens[2]);
command = MathCommand.valueOf(tokens[0]);

}

@Override
public String toString() {
String result1 ="";
if(command==MathCommand.Add)
result1 = leftValue+" + "+rightValue+" = "+result;
if(command==MathCommand.Subtract)
result1 = leftValue+" - "+rightValue+" = "+result;
if(command==MathCommand.Multiply)
result1 = leftValue+" * "+rightValue+" = "+result;
if(command==MathCommand.Divide)
result1 = leftValue+" / "+rightValue+" = "+result;
return result1;
}

@Override
public void calculate() {

switch (command)
{
case Add:
Adder add = new Adder(leftValue,rightValue);
add.calculate();
result = add.getResult();
break;
case Subtract:
Subtractor subtractor = new Subtractor(leftValue,rightValue);
subtractor.calculate();
result = subtractor.getResult();
break;
case Multiply:
Multiplier multiplier = new Multiplier(leftValue,rightValue);
multiplier.calculate();
result = multiplier.getResult();
break;
case Divide:
Divider divider = new Divider(leftValue,rightValue);
divider.calculate();
result = divider.getResult();
break;
}
}
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

1.I have changed Hw05Source.java file completly

2.create new exception class InvalidStatementException.java

3.i have changed process method of CalculateHelper.java

Incorrect number of fields: Add 1.0 Non-numeric data: Add xx 25.0 Original exception: For input string: xx Invalid command: A

//Hw05Source.java
public class Hw05Source {
public static void main(String[] args) {
String[] equations = {
   "Add 1.0",
   "Add xx 25.0",
   "Addx 0.0 0.0",
"Divide 100.0 50.0",
"Add 25.0 92.0",
"Subtract 225.0 17.0",
"Multiply 11.0 3.0"
};
CalculateHelper helper = new CalculateHelper();
for (int i = 0; i < equations.length; i++){
       try{
helper.process(equations[i]);
helper.calculate();
System.out.println(helper);
       }catch(InvalidStatementException e){
           System.out.println(e.getMessage());
           if(e.getCause()!=null){
               System.out.println("\tOriginal exception: "+e.getCause().getMessage());
           }
       }
}
}
}

//process method of CalculateHelper.java

public void process(String equation) throws InvalidStatementException {
String[] tokens = equation.split(" ");
if(tokens.length!=3)
       throw new InvalidStatementException("Incorrect number of fields",equation);
if(!tokens[1].matches("-?\\d+(.\\d+)?")){
   throw new InvalidStatementException("Non-numeric data",equation,new Throwable("For input string: "+tokens[1]));
}
if(!tokens[2].matches("-?\\d+(.\\d+)?")){
   throw new InvalidStatementException("Non-numeric data",equation,new Throwable("For input string: "+tokens[2]));
}
if(!(tokens[0].equals("Add") || tokens[0].equals("Subtract") ||
   tokens[0].equals("Multiply") || tokens[0].equals("Divide"))){
   throw new InvalidStatementException("Invalid command",equation);
}
leftValue = Double.parseDouble(tokens[1]);
rightValue = Double.parseDouble(tokens[2]);
command = MathCommand.valueOf(tokens[0]);
}

InvalidStatementException.java

class InvalidStatementException extends Exception
{
public InvalidStatementException(String reason,String statement)
{
super(reason+": "+statement);
}
public InvalidStatementException(String reason,String statement,Throwable cause)
{
super(reason+": "+statement,cause);
}
}

////////////////////////////////////

Adder.java
CalculateBase.java
CalculateHelper.java
Divider.java
Hw05Source.java
InvalidStatementException.java
MathCommand.java
MathEquation.java
Multiplier.java
Subtractor.java

Explanation:

i have created user defined exception class InvlidStatementException.java which has 2 parametrized constructor which has both reason & statement another constructor with one more paramter throwable paramter

this below statement is to throw an exception when user forgot to enter two values for operations like Add 1.0

if(tokens.length!=3)
       throw new InvalidStatementException("Incorrect number of fields",equation);

this below statement is to throw an exception when user enter non numberic field for calculatoin operation

if(!tokens[1].matches("-?\\d+(.\\d+)?")){
   throw new InvalidStatementException("Non-numeric data",equation,new Throwable("For input string: "+tokens[1]));
}
if(!tokens[2].matches("-?\\d+(.\\d+)?")){
   throw new InvalidStatementException("Non-numeric data",equation,new Throwable("For input string: "+tokens[2]));
}

this below statement is to throw an exceptioon if the user enter invalid code for operation

if(!(tokens[0].equals("Add") || tokens[0].equals("Subtract") ||
   tokens[0].equals("Multiply") || tokens[0].equals("Divide"))){
   throw new InvalidStatementException("Invalid command",equation);
}

Add a comment
Know the answer?
Add Answer to:
In Java. Please use the provided code Homework 5 Code: public class Hw05Source { public static...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • The current code I have is the following: package uml; public class uml {        public...

    The current code I have is the following: package uml; public class uml {        public static void main(String[] args) {              // TODO Auto-generated method stub        } } class Account { private String accountID; public Account(String accountID) { this.accountID = accountID; } public String getAccountID() { return accountID; } public void setAccountID(String accountID) { this.accountID = accountID; } @Override public String toString() { return "Account [accountID=" + accountID + "]"; } } class SuppliesAccount extends Account { private...

  • please help me add on this java code to run public class CarHwMain public static void...

    please help me add on this java code to run public class CarHwMain public static void main(String args 1/ Construct two new cars and one used car for the simulation Cari carl = new Car W"My New Mazda", 24.5, 16.0); Car car2 = new Cart My New Ford" 20.5, 15.0) Cari car) - new Cari ("My Used Caddie", 15.5, 16.5, 5.5, 1/ ADD CODE to completely fill the tanks in the new cars and off the used cars ton //...

  • What is wrong with the following Java Code. public class TestEdible { abstract class Animal {...

    What is wrong with the following Java Code. public class TestEdible { abstract class Animal { /** Return animal sound */ public abstract String sound(); } class Chicken extends Animal implements Edible { @Override public String howToEat() { return "Chicken: Fry it"; } @Override public String sound() { return "Chicken: cock-a-doodle-doo"; } } class Tiger extends Animal { @Override public String sound() { return "Tiger: RROOAARR"; } } abstract class Fruit implements Edible { // Data fields, constructors, and methods...

  • Help to fix Java GUI CALCULATOR code: This is a partial part of the program. When...

    Help to fix Java GUI CALCULATOR code: This is a partial part of the program. When i divide 16/6, i get 3. I don't want it to round up but I want it in decimal eg: 16/6 = 2.66666667 Code: public class Calculator1 extends javax.swing.JFrame {    double firstnum = 0.0;    double secondnum = 0.0;    double result = 0.0;        String operation;        public Calculator1() {        initComponents();    }        private void jBtnEqualActionPerformed(java.awt.event.ActionEvent evt) {                                                   secondnum = Double.parseDouble(jtxtDisplay.getText());        String answer;        switch(operation)...

  • COVERT TO PSEUDOCODE /****************************Vacation.java*****************************/ public abstract class Vacation {    /*    * private data field...

    COVERT TO PSEUDOCODE /****************************Vacation.java*****************************/ public abstract class Vacation {    /*    * private data field    */    private double cost;    private double budget;    private String destination;    /**    *    * @param cost    * @param budget    * @param destination    */    public Vacation(double cost, double budget, String destination) {        super();        this.cost = cost;        this.budget = budget;        this.destination = destination;    }    //getter and...

  • In the processLineOfData, write the code to handle case "H" of the switch statement such that:...

    In the processLineOfData, write the code to handle case "H" of the switch statement such that: An HourlyEmployee object is created using the firstName, lastName, rate, and hours local variables. Notice that rate and hours need to be converted from String to double. You may use parseDouble method of the Double class as follows:               Double.parseDouble(rate) Call the parsePaychecks method in this class passing the HourlyEmployee object created in the previous step and the checks variable. Call the findDepartment method...

  • Cant figure out how to fix error Code- import java.io.File; import java.io.IOException; import java.util.*; public class Program8 {    public static void main(String[] args)throws IOException{       ...

    Cant figure out how to fix error Code- import java.io.File; import java.io.IOException; import java.util.*; public class Program8 {    public static void main(String[] args)throws IOException{        File prg8 = new File("program8.txt");        Scanner reader = new Scanner(prg8);        String cName = "";        int cID = 0;        double bill = 0.0;        String email = "";        double nExempt = 0.0;        String tExempt = "";        int x = 0;        int j = 1;        while(reader.hasNextInt()) {            x = reader.nextInt();}        Customers c1 [] = new Customers [x];        for (int...

  • Assignment (to be done in Java): Person Class: public class Person extends Passenger{ private int numOffspring;...

    Assignment (to be done in Java): Person Class: public class Person extends Passenger{ private int numOffspring; public Person() {    this.numOffspring = 0; } public Person (int numOffspring) {    this.numOffspring = numOffspring; } public Person(String name, int birthYear, double weight, double height, char gender, int numCarryOn, int numOffspring) {    super(name, birthYear, weight, height, gender, numCarryOn);       if(numOffspring < 0) {        this.numOffspring = 0;    }    this.numOffspring = numOffspring; } public int getNumOffspring() {   ...

  • How would I alter this code to have the output to show the exceptions for not...

    How would I alter this code to have the output to show the exceptions for not just the negative starting balance and negative interest rate but a negative deposit as well? Here is the class code for BankAccount: /** * This class simulates a bank account. */ public class BankAccount { private double balance; // Account balance private double interestRate; // Interest rate private double interest; // Interest earned /** * The constructor initializes the balance * and interestRate fields...

  • For Questions 1-3: consider the following code: public class A { private int number; protected String...

    For Questions 1-3: consider the following code: public class A { private int number; protected String name; public double price; public A() { System.out.println(“A() called”); } private void foo1() { System.out.println(“A version of foo1() called”); } protected int foo2() { Sysem.out.println(“A version of foo2() called); return number; } public String foo3() { System.out.println(“A version of foo3() called”); Return “Hi”; } }//end class A public class B extends A { private char service; public B() {    super();    System.out.println(“B() called”);...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT