Using Bluefish, create a Java file named Calc.java in your \"Working Directory\"
ID: 3696766 • Letter: U
Question
Using Bluefish, create a Java file named Calc.java in your "Working Directory".
Create a public class named Calc.
Request a double precision number from the user.
Request a second double precision number from the user.
Request an operation from the user. Valid inputs will be {+ - * /} - the program should display an error if an invalid operator is provided by the user.
Perform the requested calculation on the two numbers, and display the double precision answer on the screen.
Compile your program, and make sure that it works as expected.
Hint 1: Use a switch statement to select the operation to perform.
This is what I have so far....
import java.util.Scanner;
class calc{
public static void main(String args []){
Scanner calculation = new Scanner(System.in);
double num1,num2,answer;
System.out.println ("Enter your first number:");
num1 = calculation.nextDouble();
System.out.println("Enter your second number:");
num2 = calculation.nextDouble();
answer = ;
System.out.println(answer);
}
}
Explanation / Answer
import java.util.Scanner;
public class Calc {
public static void main(String args[]) {
Scanner calculation = new Scanner(System.in);
double num1, num2, answer;
System.out.print("Enter your first number:");
num1 = calculation.nextDouble();
System.out.print("Enter your second number:");
num2 = calculation.nextDouble();
System.out.print("Enter the operation:");
char operation = calculation.next().charAt(0);
switch (operation) {
case '+':
answer = num1 + num2;
System.out.println(num1 + " " + operation + " " + num2 + " = "
+ answer);
break;
case '-':
answer = num1 - num2;
System.out.println(num1 + " " + operation + " " + num2 + " = "
+ answer);
break;
case '*':
answer = num1 * num2;
System.out.println(num1 + " " + operation + " " + num2 + " = "
+ answer);
break;
case '/':
answer = num1 / num2;
System.out.println(num1 + " " + operation + " " + num2 + " = "
+ answer);
break;
default:
System.out.println("Error: Invalid operation");
break;
}
calculation.close();
}
}
OUTPUT:
Enter your first number:3
Enter your second number:4
Enter the operation:+
3.0 + 4.0 = 7.0
Enter your first number:2
Enter your second number:3
Enter the operation:-
2.0 - 3.0 = -1.0
Enter your first number:3
Enter your second number:5
Enter the operation:*
3.0 * 5.0 = 15.0
Enter your first number:6
Enter your second number:7
Enter the operation:/
6.0 / 7.0 = 0.857
Enter your first number:3
Enter your second number:2
Enter the operation:@
Error: Invalid operation
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.