Advertisement
Guest User

Untitled

a guest
Oct 7th, 2015
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1. // Arithmetic demo for El Camino High School AP Computer Science
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class Arithmetic {
  6. public static char ADD = '+';
  7. public static char SUBTRACT = '-';
  8. public static char MULTIPLY = '*';
  9. public static char DIVIDE = '/';
  10. public static char MODULUS = '%';
  11.  
  12. public static void main(String[] args) {
  13. Scanner input = new Scanner(System.in);
  14.  
  15. // Get input.
  16. System.out.print("Enter first number: ");
  17. double first = input.nextDouble();
  18. System.out.print("Enter operation: ");
  19. char operation = getOperation(input);
  20. System.out.print("Enter second number: ");
  21. double second = input.nextDouble();
  22.  
  23. // Perform operation.
  24. System.out.print("Result: ");
  25. if (operation == ADD) {
  26. System.out.println(first + second);
  27. } else if (operation == SUBTRACT) {
  28. System.out.println(first - second);
  29. } else if (operation == MULTIPLY) {
  30. System.out.println(first * second);
  31. } else if (operation == DIVIDE) {
  32. System.out.println(first / second);
  33. } else if (operation == MODULUS) {
  34. System.out.println(first % second);
  35. } else {
  36. // This should not happen. Why?
  37. }
  38. }
  39.  
  40. public static char getOperation(Scanner input) {
  41. // Get operation. from user.
  42. char operation = input.next().charAt(0);
  43. if (operation == ADD
  44. || operation == SUBTRACT
  45. || operation == MULTIPLY
  46. || operation == DIVIDE
  47. || operation == MODULUS) {
  48. // If operation is valid, return.
  49. return operation;
  50. } else {
  51. // Operation is invalid, so try again.
  52. System.out.println("Invalid operation. Try again.");
  53. return getOperation(input);
  54. }
  55. }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement