Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- /*
- =====================================================
- chapter 4: Loops
- Ex7: Subtract & Add
- =====================================================
- */
- public class MyProgram {
- public static void main(String[] args) {
- int a,b; //user input
- int add,sub; // add=a+b sub=a-b
- int newNum=0; // creating a new number containing sub & add
- int tmp,count=0; // tmp for keeping numbers in tact, count= number of digits
- char sign; // user input for the sign + -
- Scanner s=new Scanner(System.in);
- do {
- System.out.println("Enter arithmetic Expressions: (a + b)");
- a = s.nextInt();
- sign = s.next().charAt(0);
- b = s.nextInt();
- switch (sign) {
- case '+':
- sub = a - b;
- add = a + b;
- tmp = add; //keeping number in tact
- //loop counts the number of digits in the number
- while (tmp > 0) {
- tmp /= 10;
- count++;
- }
- newNum = (int) (sub * Math.pow(10, count) + add); //creating the new number
- System.out.println(a + " + " + b + " = " + newNum); // display result
- count = 0; //reset counter
- break;
- case '-':
- System.out.println("End");
- break;
- default:
- System.out.println("invalid input!");
- break;
- }
- }
- while( sign!='-' );
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement