Slip No.11
A) Write a menu driven java program using command line arguments for the following:1. Addition
2. Subtraction
3. Multiplication
4. Division.
1. Open Notepad.
2. Type the following code:
-
public class Calculator {
public static void main(String[] args) {
// Ensure the correct number of arguments are provided
if (args.length != 3) {
System.out.println("Usage: java Calculator
System.out.println("Operations: add, sub, mul, div");
return;
}
String operation = args[0];
double num1 = Double.parseDouble(args[1]);
double num2 = Double.parseDouble(args[2]);
switch (operation) {
case "add":
System.out.println("Result: " + (num1 + num2));
break;
case "sub":
System.out.println("Result: " + (num1 - num2));
break;
case "mul":
System.out.println("Result: " + (num1 * num2));
break;
case "div":
if (num2 == 0) {
System.out.println("Error: Division by zero is not allowed.");
} else {
System.out.println("Result: " + (num1 / num2));
}
break;
default:
System.out.println("Invalid operation. Please use add, sub, mul, or div.");
break;
}
}
4. Open the Command Prompt.
5. Compile the Java program by typing:
javac Calculator.java
6. Run the compiled Java program by typing:
java Calculator add 10 20
No comments:
Post a Comment