Advertisements
Hi, friends
Please, can you help me?
Q1: Write a program in java to simulate a calculator. Your program should take two numbers and an operator(+,-,*,or/), from the user in the following format: number1 operator number2 (For example 2 + 4) and print the result.Take all variables used in the program of type double.
Your program should work as long as a user wishes. Print the result up to two places of decimal.
Q2: Ask the user to enter an integer number. Write a program in java to find the factorial of a non negative integer number.
Factorial of a number is dfined as :
n! ={ 1 =======> if n = 0 , (n-1)! x n ======> if n > 0 }
(For Example 0!=1 and 1!=1 and 2!=1*2=1)
Thank you for reading :)
1)
import java.util.*; public class Calculate { public static void main(String[] args) { Scanner input=new Scanner(System.in); double num1; double num2; char operator; double result; System.out.println("Enter expressions such as 17 + 3 or 3.14159 * 4.7"); System.out.println("Use any of the operators +, -, *, /."); System.out.println("To end, enter a 0."); while (true){ System.out.println(); System.out.println("Enter Expression: "); num1 = input.nextDouble(); if (num1 == 0) break; operator = input.next().charAt(0); num2 = input.nextDouble(); switch (operator) { case '+': result = num1 + num2; break; case '-': result = num1 - num2; break; case '*': result = num1 * num2; break; case '/': result = num1 / num2; break; default: System.out.println("Unknown operator: " + operator); continue; } System.out.println("Result is " + result); } } }
2)
import java.util.*; class Factorial{ public static void main(String[] args) { Scanner input=new Scanner(System.in); System.out.print("Enter value of m: "); int m=input.nextInt(); long num=m; for(int i=m;i>1;i--){ num=num*(i-1); } System.out.println(num); } }