Calculator_Switch JavaFundamental - java

Hello I have tried syntax for calculator, with char for operand
but the result always error.
I'm using eclipse (Luna). there are no error or warning message on it.
Syntax
Scanner in = new Scanner(System.in);
int answer = 0;
System.out.println("Enter a number:");
int num1 = in.nextInt();
System.out.println("Enter another number:");
int num2 = in.nextInt();
System.out.println("Enter the operand:");
char input =(char) in.nextInt();
switch (input){
case'*':
answer = num1 * num2;
break;
case '/':
answer = num1/num2;
break;
case '%':
answer = num1%num2;
break;
case '+':
answer = num1 +num2;
break;
case '-':
answer = num1-num2;
break;
default:
System.out.println("Invalid Command");
}
System.out.println("The result is: " + answer);
Debugging
Input number, another number and an operand:
and the error:
InputMismatchException

Just change this line: char input =(char) in.nextInt(); for this char input = in.next().charAt(0)...and you are good to go!

Related

How to store value in calc and continue counting?

How to modify the code so I can continuously count? So for example 2+3=5, and than -1 =4, until i press q to exit program ?? Please some simple solution for beginners. Thank you.
import java.util.Objects;
import java.util.Scanner;
public class Calc {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
do {
System.out.println("Enter first number:");
double num1 = sc.nextDouble();
System.out.println("Enter second number");
double num2 = sc.nextDouble();
System.out.println("Select operator (+,-,*,/) or enter q to exit:");
char operator = sc.next().charAt(0);
switch (operator) {
case '+':
System.out.println("Result =" + Equasion.sum(num1, num2));
break;
case '-':
System.out.println(Equasion.substract(num1, num2));
break;
case'/':
if (num2 == 0) {
System.out.println("Divide by zero problem");
} else System.out.println(Equasion.divide(num1, num2));
case '*':
System.out.println(Equasion.multiply(num1, num2));
break;
case 'q':
System.exit(0);
}
System.out.println("Press any key to continue or q to quit");
} while (!Objects.equals(ExitProg.exitProg(), 'q'));
}
}
Correct me if I'm wrong but you should move the first lines outside the while loop then overwrite the values of num1 and num2 every iteration (num2 becomes num1, then the user inputs another num2)

Continuity Issue in Java Calculator

I am new to Java, and I'm doing a calculator APP.
I'm trying to get my calculator to keep prompting the user for the correct answer (typing Y or N) after the else statement following 'Invalid Input'.
I want the program to continue with the calculations after the correct input is finally entered.
I have played around with an embedded while loop, but ended up with an infinite loop or a loop that terminates with no resolution. The code is below.
import java.util.Scanner;
class Calculate {
public static void.main(String[] args) {
System.out.println("Welcome To Calculator!");
System.out.println("*************************************************************************");
Scanner userinput = new Scanner(System.in);
double num1, num2;
String choice;
boolean youDecide = true;
while(youDecide == true) {
System.out.println("Please enter a number: ");
num1 = userinput.nextDouble();
System.out.println("Please enter an available operator (+, -, *, /): ");
char operator = userinput.next().charAt(0);
System.out.println("Please enter another number: ");
num2 = userinput.nextDouble();
double output;
switch(operator)
{
case '+':
output = num1 + num2;
break;
case '-':
output = num1 - num2;
break;
case '*':
output = num1 * num2;
break;
case '/':
output = num1 / num2;
if(num2 == 0)
System.out.println("Math error! A number cannot be divided by zero.");
break;
default:
System.out.println("Invalid input. Please enter an available operator, i.e (+, -, *, /): ");
return;
}
System.out.println("*************************************************************************");
System.out.println("The answer is: " + "\n" + output);
System.out.println("*************************************************************************");
System.out.println("Would you like to calculate again?");
System.out.println("Please enter Y for yes, or N for no");
choice = userinput.next();
if(choice.equalsIgnoreCase("Y")) {
System.out.println("Okay. Let's continue!");
System.out.println("*************************************************************************");
youDecide = true;
}
else if(choice.equalsIgnoreCase("N")) {
System.out.println("*************************************************************************");
System.out.println("Okay. Thanks for using Calculator. Goodbye!");
System.exit(0);
}
else {
System.out.println("Invalid input. Please try again...");
System.out.println("*************************************************************************");
youDecide = false;
}
}
}
}
I've made some changes and comments to your code
import java.util.Scanner;
class Calculator {
public static void main(String[] args) {
System.out.println("Welcome To Calculator!");
System.out.println("*************************************************************************");
Scanner userinput = new Scanner(System.in);
double num1, num2;
String choice;
//the "youDecide" variable is not needed at all
while (true) {
System.out.println("Please enter a number: ");
num1 = userinput.nextDouble();
System.out.println("Please enter an available operator (+, -, *, /): ");
char operator = userinput.next().charAt(0);
System.out.println("Please enter another number: ");
num2 = userinput.nextDouble();
double output;
switch (operator) {
case '+':
output = num1 + num2;
break;
case '-':
output = num1 - num2;
break;
case '*':
output = num1 * num2;
break;
case '/':
output = num1 / num2;
if (num2 == 0) {
System.out.println("Math error! A number cannot be divided by zero.");
}
break;
default:
System.out.println("Invalid input. Please enter an available operator, i.e (+, -, *, /): ");
continue; //changed from "return" you don't want to exit, just to skip to the next execution of the loop
}
System.out.println("*************************************************************************");
System.out.println("The answer is: " + "\n" + output);
System.out.println("*************************************************************************");
System.out.println("Would you like to calculate again?");
System.out.println("Please enter Y for yes, or N for no");
choice = userinput.next();
if (choice.equalsIgnoreCase("Y")) {
System.out.println("Okay. Let's continue!");
System.out.println("*************************************************************************");
} else if (choice.equalsIgnoreCase("N")) {
System.out.println("*************************************************************************");
System.out.println("Okay. Thanks for using Calculator. Goodbye!");
System.exit(0);
} else {
System.out.println("Invalid input. Please try again...");
System.out.println("*************************************************************************");
}
}
}
}
You need a while loop to ensure the value is correct.
Due the logic into your code you need to do when the user type the char, otherwise you have to change many lines of code, or ask for all values again.
I think for a begginer the easiest way is using this loop:
char operator;
while(true) {
operator = userinput.next().charAt(0);
if(operator=='+' || operator == '-' || operator == '*' || operator == '/') {
break;
}else {
System.out.println("Please enter a valid operator: ");
}
}
Exists many ways more elegant to do this. But I think for a begginer is the easiest way to understand and implement the code.
This loop is only to ensure the user type a valid character. While the character is not one of them, the loop will be iterating.
You have to place this code just below this line where you ask for a valid operator.
After adding the edits suggested by J.F. and Javaman along with some research, I was able to solve the problem by adding the following lines to my code:
import java.util.InputMismatchException;
import java.util.Scanner;
class Calculator {
public static void main(String[] args) {
System.out.println("Welcome To Calculator!");
System.out.println("*************************************************************************");
Scanner userinput = new Scanner(System.in);
char operator;
double num1, num2;
String choice;
while(true) {
System.out.println("Please enter a number: ");
num1 = userinput.nextDouble();
System.out.println("Please enter an available operator (+, -, *, /): ");
while(true) {
operator = userinput.next().charAt(0);
if(operator == '+' || operator == '-' || operator == '*' || operator == '/') {
break;
}else {
System.out.println("Invalid input. Please enter an available operator, i.e (+, -, *, /): ");
}
}
System.out.println("Please enter another number: ");
num2 = userinput.nextDouble();
double output;
switch(operator) {
case '+':
output = num1 + num2;
break;
case '-':
output = num1 - num2;
break;
case '*':
output = num1 * num2;
break;
case '/':
output = num1 / num2;
break;
default:
System.out.println("Invalid input. Please enter an available operator, i.e (+, -, *, /): ");
continue;
}
System.out.println("*************************************************************************");
if(num2 == 0) {
System.out.println("Math error! A number cannot be divided by zero.");
}else {
System.out.println("The answer is: " + "\n" + output);
}
System.out.println("*************************************************************************");
System.out.println("Would you like to calculate again?");
System.out.println("Please enter Y for yes, or N for no");
choice = userinput.next();
if(choice.equalsIgnoreCase("Y")) {
System.out.println("Okay. Let's continue!");
System.out.println("*************************************************************************");
}else if(choice.equalsIgnoreCase("N")) {
System.out.println("*************************************************************************");
System.out.println("Okay. Thanks for using Calculator. Goodbye!");
System.exit(0);
}else {
System.out.println("Invalid input. Please try again...");
System.out.println("*************************************************************************");
**while (!("Y").equalsIgnoreCase(choice) && !("N").equalsIgnoreCase(choice)) {
System.out.println("Invalid input. Please try again...");
System.out.println("*************************************************************************");
System.out.println("Please enter Y for yes, or N for no");
choice = userinput.next();
if(choice.equalsIgnoreCase("Y")) {
System.out.println("Okay. Let's continue!");
System.out.println("*************************************************************************");
}else if(choice.equalsIgnoreCase("N")) {
System.out.println("*************************************************************************");
System.out.println("Okay. Thanks for using Calculator. Goodbye!");
System.exit(0);**
}
}
}
}
}
}

a simple calculator with switch case

I have a problem. In class we have to do a simple calculator, and my problem is that I wanna write a number, then the operator, then again a number. Somehow my code doesn't work. I can enter the first number but then my program closes :/ Why is that? Is it because I used the data type string?
Thanks to everyone in advance!!
Here is my code:
import java.util.Scanner;
import java.math.*;
public class Calculatrice
{
public static void main(String args[])
{
double num1;
Scanner keyb = new Scanner(System.in);
System.out.println("Calculette Simple");
System.out.print("Valeur actuelle: ");
num1 = keyb.nextDouble();
System.out.print("Entrez un operateur: ");
String i;
i = keyb.nextLine();
double result = 0;
switch (i)
{
case "+":
result = result + num1;
break;
case "-":
result = result - num1;
break;
case "*":
result = result * num1;
break;
case "/":
result = result / num1;
break;
case "sqrt":
result = Math.sqrt(result);
break;
case "c":
result = 0;
break;
case "x":
System.exit(0);
break;
case "^":
result = Math.pow(result,num1);
break;
default:
System.out.println("Valeurs acceptees: +, -, *, /, ^, sqrt, c, x");
break;
}
keyb.close();
}
}
You need a loop: you need to read data from command line until a condition is verified, in order to read more then one string (number, operator or whatever you want). Then try something like this :
// your initialization of scanner
i = keyb.nextLine();
double result = 0;
while (!i.equals("end")) { // I use this as exit condition, but you can use whatever you want
switch (i) {
case "+":
result = result + num1;
break;
case "-":
result = result - num1;
break;
case "*":
result = result * num1;
break;
case "/":
result = result / num1;
break;
case "sqrt":
result = Math.sqrt(result);
break;
case "c":
result = 0;
break;
case "x":
System.exit(0);
break;
case "^":
result = Math.pow(result, num1);
default:
System.out.println("Valeurs acceptees: +, -, *, /, ^, sqrt, c, x");
}
}
// close scanner
you need some loop with exit condition (I belive it's 'x' in input)
something like
while (!"x".equals(i)) {
switch (i)
...
}
The program takes the value of both the numbers (entered by user) and then user is asked to enter the operation (+, -, * and /), based on the input program performs the selected operation on the entered numbers using switch case.
import java.util.Scanner;
public class JavaExample {
public static void main(String[] args) {
double num1, num2;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number:");
/* We are using data type double so that user
* can enter integer as well as floating point
* value
*/
num1 = scanner.nextDouble();
System.out.print("Enter second number:");
num2 = scanner.nextDouble();
System.out.print("Enter an operator (+, -, *, /): ");
char operator = scanner.next().charAt(0);
scanner.close();
double output;
switch(operator)
{
case '+':
output = num1 + num2;
break;
case '-':
output = num1 - num2;
break;
case '*':
output = num1 * num2;
break;
case '/':
output = num1 / num2;
break;
/* If user enters any other operator or char apart from
* +, -, * and /, then display an error message to user
*
*/
default:
System.out.printf("You have entered wrong operator");
return;
}
System.out.println(num1+" "+operator+" "+num2+": "+output);
}
}

Why is my programming not looping correctly? (Java)

Desired output: Hello, I am trying to make a program that does addition, subtraction, multiplication, and division and loops until you press 'e' to exit the loop.
So, I want it to look something like this:
A. Addition
B. Subtraction
C. Multiplication
D. Division
E. Exit
Please enter your selection, enter E to end:
//let's say they enter a, and want to add 5 plus 5
Enter your first number:
Enter your second number:
5 + 5 = 10.0
Please enter your selection, enter E to end:
//This looping part is what I want to happen! But my program just ends, and I'm not
sure how to fix it
Issue: My problem is that once you enter what operation you want, it only does the arithmetic once and then it displays my exit message and ends, but that is only supposed to happen when the user enters 'e' but the rest works, I think!
Here is my code
import java.util.Scanner;
public class Calculator_Loop {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
char selection;
char choice = 'E';
double num_1;
double num_2;
double result;
System.out.println("A. Addition\nB. Subtraction\nC. Multiplication\nD. Division \n\nE. Exit");
//System.out.println("\nPlease enter your selection, enter E to end:");
//selection = input.next().charAt(0);
//choice = Character.toUpperCase(selection);
while(choice != 'E')
System.out.println("\nPlease enter your selection, enter E to end:");
selection = input.next().charAt(0);
choice = Character.toUpperCase(selection);
if(choice == 'A') {
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 + num_2;
System.out.println(result);
}
if(choice == 'B'){
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 - num_2;
System.out.println(result);
}
if(choice == 'C'){
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 * num_2;
System.out.println(result);
}
if(choice == 'D'){
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 / num_2;
System.out.println(result);
}
System.out.println("Thank you, have a nice day!");
}
}
Am I doing something wrong with the brackets? Or is there something I'm missing for the loop to work? Any help is appreciated, thanks!
Welcome to SO.
Problem is (as far as I can see) that you have nothing/only the print line in your while loop.
while(true) {
do things
}
Java allows while loops without brackets, but at maximum one line (and I recommend doing them for one line too, but that is debattable), as soon as you need several lines, you need brackets and should have according indentation.
You need to surround your intended while loop with brackets to make it work the way you want:
while (choice != 'E') {
System.out.println("\nPlease enter your selection, enter E to end:");
selection = input.next().charAt(0);
choice = Character.toUpperCase(selection);
switch (choice) {
case 'A':
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 + num_2;
System.out.println(result);
break;
case 'B':
// ...
}
}
System.out.println("Thank you, have a nice day!");
Currently, your while loop will spin forever (I think), because the seed value for choice is being set to E.
Side note: Consider using a switch statement to handle the various case values for the choice.
Instead of using the if conditions, please use the while loop and switch condition. if the input value is other than the A, B, C or D then exit from the code.
Code takes only the first character of your input and enters into switch case, where it will compare the input with the required conditions.
public class Calculator_Loop {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String choice = "";
double num_1;
double num_2;
double result;
System.out.println("A. Addition\nB. Subtraction\nC. Multiplication\nD. Division \n\nE. Exit");
/*System.out.println("\nPlease enter your selection, enter E to end:");
selection = input.next().charAt(0);
choice = input.next().substring(0, 1).toUpperCase();*/
outer: while (true) {
System.out.println("\nPlease enter your selection, enter E to end:");
choice = input.next();
choice = choice.substring(0, 1).toUpperCase();
switch (choice) {
case "A":
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 + num_2;
System.out.println(result);
break;
case "B":
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 - num_2;
System.out.println(result);
break;
case "C":
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 * num_2;
System.out.println(result);
break;
case "D":
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 / num_2;
System.out.println(result);
break;
default:
System.out.println("Thank you, have a nice day!");
break outer;
}
}
}
}
You class has two problems.
One is the missing brace that others metioned.
The other is that it will never enter the loop as the condition is allways false.
So to make sure that the loop is entered at least once you need an endcondition. a do-while construct instead of your startcondition.
So I changed your while loop into a do-while. By that I added the missing curly.
I also changed your if's to a switch as a choice calls for it.
And I moved the question into the loop, so the user gets the information in every iteration.
import java.util.Scanner;
public class Calculator_Loop {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
char selection;
char choice = 'E';
double num_1;
double num_2;
double result;
do {
System.out.println("A. Addition\nB. Subtraction\nC. Multiplication\nD. Division \n\nE. Exit");
//System.out.println("\nPlease enter your selection, enter E to end:");
//selection = input.next().charAt(0);
//choice = Character.toUpperCase(selection);
System.out.println("\nPlease enter your selection, enter E to end:");
selection = input.next().charAt(0);
choice = Character.toUpperCase(selection);
switch (choice) {
case 'A':
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 + num_2;
System.out.println(result);
break;
case 'B':
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 - num_2;
System.out.println(result);
break;
case 'C':
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 * num_2;
System.out.println(result);
break;
case 'D':
System.out.println("Enter your first number:");
num_1 = input.nextDouble();
System.out.println("Enter your second number:");
num_2 = input.nextDouble();
result = num_1 / num_2;
System.out.println(result);
break;
}
} while (choice != 'E');
System.out.println("Thank you, have a nice day!");
}
}

Java - Getting the answer to a calculation using variables

How can I return the answer to a calculation where the two numbers and operator used are stored in variables (input from the user).
I am creating a simple calculator and trying to output the answer to "Number" "Operator" "Number2" which can be anything depending on what the user inputs.
int Number;
int Number2;
int Operator;
String OperatorString;
do
{
System.out.println("Enter a number");
Number = UserInputScanner.nextInt();
System.out.println("1. + \n");
System.out.println("2. - \n");
System.out.println("3. * \n");
System.out.println("4. / \n");
Operator = UserInputScanner.nextInt();
switch (Operator) {
case 1: OperatorString = "+";
break;
case 2: OperatorString = "-";
break;
case 3: OperatorString = "*";
break;
case 4: OperatorString = "/";
break;
default: OperatorString = "Invalid Operator";
break;
}
System.out.println(OperatorString);
System.out.println("Enter another number");
Number2 = UserInputScanner.nextInt();
Answer = "Number" + "OperatorString" + "Number2";
System.out.println(Number + OperatorString + Number2 + "=" + Answer);
The output from this when inputting these numbers and operator returns "5+5=5+5" and I am trying to return "5+5=10".
Java provides no built-in way of evaluating a String expression with operators to produce a value of the result, so you would need another switch to compute Answer:
switch (Operator) {
case 1: Answer = Number + Number2;
break;
case 2: Answer = Number - Number2;
break;
case 3: Answer = Number * Number2;
break;
case 4: Answer = Number / Number2;
break;
default: Answer = 0;
break;
}
The structure of the switch is identical to the one that you have before reading the second number, so you can combine the two if you move the reading of Number2 before the switch.
Calculate the answer in Switch block itself
int Number;
int Number2;
int Operator;
String OperatorString;
do
{
System.out.println("Enter a number");
Number = UserInputScanner.nextInt();
System.out.println("1. + \n");
System.out.println("2. - \n");
System.out.println("3. * \n");
System.out.println("4. / \n");
Operator = UserInputScanner.nextInt();
System.out.println("Enter another number");
Number2 = UserInputScanner.nextInt();
switch (Operator) {
case 1: OperatorString = "+";
Answer = Number + Number2;
break;
case 2: OperatorString = "-";
Answer = Number - Number2;
break;
case 3: OperatorString = "*";
Answer = Number * Number2;
break;
case 4: OperatorString = "/";
Answer = Number / Number2;
break;
default: OperatorString = "Invalid Operator";
break;
}
System.out.println(OperatorString);
System.out.println(Number + OperatorString + Number2 + "=" + Answer);

Categories

Resources