Advertisement
hpilo

Chapter4_Loops_Ex7

Dec 15th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.77 KB | None | 0 0
  1. import java.util.Scanner;
  2. /*
  3.     =====================================================
  4.                    chapter 4: Loops
  5.  
  6.       Ex7: Subtract & Add
  7.     =====================================================
  8. */
  9.  
  10.  
  11. public class MyProgram {
  12.     public static void main(String[] args) {
  13.  
  14.         int a,b;             //user input
  15.         int add,sub;        // add=a+b    sub=a-b
  16.         int newNum=0;      //  creating a new number containing sub & add
  17.         int tmp,count=0;  //   tmp for keeping numbers in tact, count= number of digits
  18.         char sign;       //    user input for the sign + -
  19.         Scanner s=new Scanner(System.in);
  20.  
  21.         do {
  22.             System.out.println("Enter arithmetic Expressions: (a + b)");
  23.  
  24.             a = s.nextInt();
  25.             sign = s.next().charAt(0);
  26.             b = s.nextInt();
  27.  
  28.             switch (sign) {
  29.  
  30.                 case '+':
  31.  
  32.                     sub = a - b;
  33.                     add = a + b;
  34.  
  35.                     tmp = add;  //keeping number in tact
  36.  
  37.                     //loop counts the number of digits in the number
  38.                     while (tmp > 0) {
  39.                         tmp /= 10;
  40.                         count++;
  41.                     }
  42.  
  43.  
  44.                     newNum = (int) (sub * Math.pow(10, count) + add);    //creating the new number
  45.                     System.out.println(a + " + " + b + " = " + newNum); // display result
  46.                     count = 0;  //reset counter
  47.  
  48.                     break;
  49.  
  50.                 case '-':
  51.                     System.out.println("End");
  52.                     break;
  53.  
  54.                 default:
  55.                     System.out.println("invalid input!");
  56.                     break;
  57.             }
  58.         }
  59.             while( sign!='-' );
  60.  
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement