Sunday, April 7, 2013

Fractions Calculator program

The FractionCalculator program is able to add, subtract, multiply, and divide two fractions. The program asks the user to choose one of the four operations and the two fractions. In this program, you will learn the following things about Java programming language:
-creating class and objects,
-defining class constructors,
-defining class private data and public method members,
-accessing class members, and
-using switch case statement for multiple choice problem.

FractionCalculator source code:

1   import java.io.*;
2   import java.util.Scanner;
3   class FractionCalculator{
4       class Fraction{
private int nomo;
private int deno;
Fraction(){nomo=0;deno=1;}
Fraction(int n,int d){nomo=n;deno=d;}

5 }

6 private static Fraction f1;
7 private static Fraction f2;


8     public static void main(String[] args){
9     int choi;
10 Scanner sc=new Scanner(System.in);
11 FractionCalculator FC=new FractionCalculator();
12 Fraction f;
13 printMenu();
System.out.print("Choose one operation:");
14 choi=sc.nextInt();
15       switch(choi){
16 case 1: FC.getInput();
f=FC.addFraction(f1,f2);
System.out.format("\nResult:%d/%d\n",f.nomo,f.deno);
break;
17 case 2: FC.getInput();
f=FC.subtractFraction(f1,f2);
System.out.format("\nResult:%d/%d\n",f.nomo,f.deno);
break;
18 case 3: FC.getInput();
f=FC.multiplyFraction(f1,f2);
System.out.format("\nResult:%d/%d\n",f.nomo,f.deno);
break;
19 case 4: FC.getInput();
f=FC.divideFraction(f1,f2);
System.out.format("\nResult:%d/%d\n",f.nomo,f.deno);
break;
default: System.out.println("Invalid choice!");
20         }
21    }

22    public Fraction addFraction(Fraction f1,Fraction f2){
Fraction resul=new Fraction();
resul.nomo=(f1.nomo*f2.deno)+(f1.deno*f2.nomo);
resul.deno=f1.deno*f2.deno;
return resul;
23 }
24   public Fraction subtractFraction(Fraction f1,Fraction f2){
Fraction resul=new Fraction();
resul.nomo=(f1.nomo*f2.deno)-(f1.deno*f2.nomo);
resul.deno=f1.deno*f2.deno;
return resul;
25 }
26  public Fraction multiplyFraction(Fraction f1,Fraction f2){
Fraction resul=new Fraction();
resul.nomo=f1.nomo*f2.nomo;
resul.deno=f1.deno*f2.deno;
return resul;
27 }
28  public Fraction divideFraction(Fraction f1,Fraction f2){
Fraction resul=new Fraction();
resul.nomo=f1.nomo*f2.deno;
resul.deno=f1.deno*f2.nomo;
return resul;
29 }
30 public static void printMenu(){
System.out.println("FRACTIONS CALCULATOR");
System.out.println("-------------------------------");
System.out.println("1. Add fractions");
System.out.println("2. Subtract fractions");
System.out.println("3. Multiply fractions");
System.out.println("4. Divide fractions");
31 }
32 public void getInput(){
String[] ftext=new String[2];
                 String[] sptext=new String[2];
int no,de;
f1=new Fraction();
f2=new Fraction();
int i;

try{
for(i=0;i<=1;i++){
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
      System.out.format("Enter fraction %d (e.g. 1/2):",i+1);
ftext[i]=br.readLine();

}
sptext=ftext[0].split("/");
f1.nomo=Integer.parseInt(sptext[0]);
f1.deno=Integer.parseInt(sptext[1]);

sptext=ftext[1].split("/");
f2.nomo=Integer.parseInt(sptext[0]);
f2.deno=Integer.parseInt(sptext[1]);
if(f1.deno==0 || f2.deno==0) { System.out.println("A denominator can't be zero."); System.exit(100);}

}catch(IOException e){System.out.println("Error in reading user input...");}
34    }
35  }


Program Output
Java fraction calculator program

Code Explanation:
1  Include all classes in io package in the program. This program needs BufferedReader, InputStreamReader, and IOException classes from this package.
2  Include Scanner class used to get number input from keyboard.
3  Open FractionCalculator class block.
4  Define Fraction class. This class is a template for fraction objects. It has two private data member: nomo and deno to store the nominator and denominator of a fraction object. It also has two constructors. One constructor without argument is a default constructor. Another constructor has two arguments. The latter can be used to assign nominator value and denominator value to a fraction object when it is created by using the new keyword.
5  Close Fraction class block.
6  Declare private data member f1 of the FractionCalculator class. The f1 member is used to store the first fraction input by the user. It is declared with static keyword. This will make it a static member. A static data member can be used in a static method and can be accessed without creating an object.
7  Declare private data member f2 of the FractionCalculator class. It is to store the second fraction input by user.
8  Open the main method block.
9  Declare local variable choi for storing a choice input by the user.
10  Create Scanner object sc to receive value input.
11  Create FractionCalculator object FC.
12  Delcare local variable f as Fraction type. It is used to store result fraction.
13  Show calculator menu.
14  Receive choice input.
15  The switch statement is used to check multiple choices. Each choice is checked by case statement.
The break keyword is used to break a loop. It can also be used in the switch statement. It is used in each block of case to confine the work in the current case block that satisfies the choice. Therefore, you can make sure that the process does not slip to next case block.
16  Check whether the choice 1 (add fractions) is chosen.
17  Check whether the choice 2 (subtract fractions) is chosen.
18  Check whether the choice 3 (multiply fractions) is chosen.
19  Check whether the choice 4 (divide fractions) is chosen.
20  Close switch block.
21  Close the main method block.
22  Define the addFraction method to add fractions.
23  Close the addFraction method block.
24  Define the subtractFraction method to subtract fractions.
25  Close the subtractFraction method block.
26  Define the multiplyFraction method to multiply fractions.
27  Close the multiplyFraction method block.
28  Define the divideFraction method to divide fractions.
29  Close the divideFraction method block.
30  Define printMenu method to display calculator menu.
31  Close printMenu method block.
32  Define the getInput method. In this method, two array objects are used. The first one is ftext that is used to store the text of the first and second fractions. The program allows the user to input a fraction in a text format (e.g. 1/2). And the second--array sptext is used to store the text of nominator and denominator of a fraction string. The text of nominator and denominator are taken from the first array by splitting the it in to two parts by using the split method of the string object. The separator character used to split the fraction text in to nominator and denominate is '/'. The text of nominator and denominator are converted to  integer type by using the parseInt method of Integer class because each fraction object stores its nominator and denominator as integer values. A fraction can not have zero denominator. So we check this case before any operation can be performed on the fractions.

33 Close the getInput method block.
34 Close the FractionCaluclator class block.

Note:
1. To create an object from a class, the new keyword is used.
2. You can have a class with multiple constructors.
3. To access a public member of an object you can use the form: obj.member_name.

6 comments:

  1. The calculation of your annuity is most important part of your investment, and everyone needs to calculate their annuity before doing investment. The Annuity Calculator helps the people a lot in the making of calculation of their investment annuity.

    ReplyDelete
  2. With the economies and technologies growing at a rapid pace, the need had been felt wide and across to have calculators that could perform all basic functions automatically and quickly.guarantor loans

    ReplyDelete
  3. Learnt a great deal about amortization from your site. Very useful and informative webpage indeed. amortization

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. I believe that in this age of equality and government monitoring we should have reached a point where everyone is treated the same and everyone is entitled to the same mortgage deal. mortgage advice manchester

    ReplyDelete
  6. Calculator is very useful for Trigonometry, Calculus, and advanced mathematics subjects. There are also other calculator that are best for specific purpose such as fraction calculator for solving fraction problems. Scientific calculator is also best for Chemistry, Physics, and engineering subjects.

    ReplyDelete