Advertisement
binibiningtinamoran

AddOrMultiply

Sep 2nd, 2019
181
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.52 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class AddOrMultiply {
  4.  
  5.     public static void main(String []args) {
  6.  
  7.         enterNumber();
  8.     }
  9.  
  10.     public static void enterNumber() {
  11.         int userNumber;
  12.         char userChar;
  13.         Scanner obj = new Scanner(System.in);
  14.         do {
  15.             System.out.print("Enter an integer number: ");
  16.             userNumber = obj.nextInt();
  17.  
  18.             if (userNumber == 0) {
  19.                 break;
  20.             } else {
  21.                 System.out.print("Enter either \'a\' or \'m\' ");
  22.                 userChar = obj.next().charAt(0);
  23.  
  24.                 while (userChar != 'a' && userChar != 'm') {
  25.                     System.out.println("Invalid choice made.");
  26.                     System.out.print("Enter either \'a\' or \'m\' ");
  27.                     userChar = obj.next().charAt(0);
  28.                 }
  29.  
  30.                 if (userChar == 'a') {
  31.                     System.out.printf("The sum is %,d\n", getSum(userNumber));
  32.                 } else {
  33.                     System.out.printf("The product is %,d\n", getProduct(userNumber));
  34.                 }
  35.             }
  36.         } while (userNumber > 0);
  37.  
  38.     }
  39.  
  40.     public static long getSum(int input) {
  41.  
  42.         if (input > 1) {
  43.             return input + getSum(input - 1);
  44.         } else {
  45.             return 1;
  46.         }
  47.     }
  48.  
  49.     public static long getProduct(int input) {
  50.         if (input >= 1) {
  51.             return input * getProduct(input - 1);
  52.         } else {
  53.             return 1;
  54.         }
  55.     }
  56.  
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement