In: Computer Science
Modify the following java code, utilizing a loop mechanism to
enable the user to use the calculator more than once.
The program does the following:
It prompts the user to enter 2 numbers.
It prompts the user to choose an operation to perform
on those numbers:
Operation 1: Addition.
Operation 2: Subtraction.
Operation 3: Multiplication.
Operation 4: Division.
It outputs the result of the operation.
It asks the user if they want to perform another
calculation, using “-1" as a stop value.
The code:
package udh;
import java.util.Scanner;
public class Udh {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter two numbers");
int num1 = input.nextInt();
int num2 = input.nextInt();
System.out.println("Choose the operator; *, /, +, - ");
char choice = input.next().charAt(0);
switch (choice)
{
case '+':
int add= num1+num2;
System.out.println(add);
break;
case '-':
int sub = num1-num2;
System.out.println(sub);
break;
case '*':
int mul= num1*num2;
System.out.println(mul);
break;
case '/':
double div= num1/num2;
System.out.println(div);
break;
default :
System.out.println("Invalid operator");
}
}
}
To enable the user to do multiple calculations we use do-while loop. We take a variable "next" and if the user does not wants to calculate further, then next = -1.
The code is as follows:
package udh;
import java.util.Scanner;
public class Udh {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int next; //next variable decides whether to calculate more based on user choice
do{
System.out.println("Enter two numbers");
int num1 = input.nextInt();
int num2 = input.nextInt();
System.out.println("Choose the operator; *, /, +, - ");
char choice = input.next().charAt(0);
switch (choice){
case '+':
int add= num1+num2;
System.out.println(add);
break;
case '-':
int sub = num1-num2;
System.out.println(sub);
break;
case '*':
int mul= num1*num2;
System.out.println(mul);
break;
case '/':
double div= (double)num1/num2;
System.out.println(div);
break;
default :
System.out.println("Invalid operator");
}
//Taking input for stopping
System.out.println("Another calculation? (Type -1 to stop)");
next = input.nextInt(); //Assignment of value to next
}while(next!=-1); //Do while loop for multiple calculations. It iterates if next is not -1
System.out.println("Bye Bye!!");
input.close();
}
}
Output:
Hope this helps
If you have any doubt feel free to comment
Thank You!!