I created simple calculator using switch case. When I enter the invalid operators, but it takes that value .And at last it gives the default switch case .How can I restrict it.
package calculator;
import java.util.*;
public class Calculator {
public static void main(String[] args) {
char operator;
Double num1, num2, result;
Scanner input = new Scanner(System.in);
System.out.println("Enter the operator: +,-,*,/,% ");
operator = input.next().charAt(0);
//user input
System.out.println("Enter the First Number:");
num1 = input.nextDouble();
System.out.println("Enter the Second Number:");
num2 = input.nextDouble();
switch (operator) {
case '+':
result = num1+num2;
System.out.println(num1+" + "+num1+" = " + result);
break;
case '-':
result = num1-num2;
System.out.println(num1+" - "+num1+" = " + result);
break;
case '*':
result = num1*num2;
System.out.println(num1+" * "+num1+" = " + result);
break;
case '/':
result = num1/num2;
System.out.println(num1+" / "+num1+" = " + result);
break;
case '%':
result = num1%num2;
System.out.println(num1+" % "+num1+" = " + result);
break;
default:
System.out.println("Invalid operator");
break;
}
input.close();
}
}
console output
Enter the operator: +,-,*,/,%
7
Enter the First Number:
5
Enter the Second Number:
5
Invalid operator
if(Character.isDigit(c)){
// what you want for true
}
else{
// what you want for false
}
This may help you.
Java or any other programming languages run code sequentially.
Here once the operator is entered you can check to proceed further for other statements.
The logic of code how you write, that way it is executed.
So in this case, once you take value for operator check whether that operator is allowed in your case or not.
If allowed then run the further code else not run that.
Related
I am trying to develop a calculator program that inputs an arithmetic expression of the form number operator number = and computes the result of the expression. The expression will be evaluated from left to right not considering regular operator precedence. For example, the expression 14 - 5 * 3 = will produce 27.0. The value = displays the final result and terminates the program.
I've been trying to fix this for a couple of days now, but it outputs the wrong answer whenever I enter an expression with more than two numbers. For instance, 2.8 + 2 - 9.5 should equal -4.7 but the program outputs -6.7. Any idea why that is the case?
import java.util.Scanner;
public class Calculator {
// Compute an arithmetic expression
public static void main(String[] args) {
// Declare the identifiers
final String END = "=";
String input;
double num1 = 0;
double num2 = 0;
char operator = 0;
Scanner scnr = new Scanner (System.in);
System.out.println("Enter your numeric expression in the following form: ");
System.out.println("number operator number operator number = ");
System.out.println("Leave a blank space after each number or operator.");
System.out.println("Example: 3.5 * 3 - 5 / 2.5 =");
// Input the first item
System.out.print("> ");
input = scnr.next();
// Process the first item and input and process the rest of the items
while (!input.equals(END)){
switch (input){
case "+":
operator = '+';
System.out.println("> Operator is: " + operator);
break;
case "-":
operator = '-';
System.out.println("> Operator is: " + operator);
break;
case "*":
operator = '*';
System.out.println("> Operator is: " + operator);
break;
case "/":
operator = '/';
System.out.println("> Operator is: " + operator);
break;
default: // a number was entered
if (num1 == 0) {
num1 = Double.parseDouble(input);
System.out.println("> Num1 is: " + num1);
}
else {
num2 = Double.parseDouble(input);
System.out.println("> Num2 is: " + num2);
}
} // end of switch
if (num1 != 0 && num2 != 0) {
System.out.println("Num2 before calc is " + num2);
switch (operator) {
case '+':
num2 = num1 + num2;
break;
case '-':
num2 = num1 - num2;
break;
case '*':
num2 = num1 * num2;
break;
case '/':
num2 = num1 / num2;
break;
default:
}
}
input = scnr.next();
} // end of while-loop
// Display the answer
System.out.println("> Answer is: " + num2);
System.out.println("Have a nice day!");
}
}
In order to make it work, try to:
in your 2nd switch statement, change num2 = num1 + num2; into num1 = num1 + num2;. Do this for all cases;
I added an isOperator boolean to skip computing the operation if input is an operator.
Full code below:
import java.util.Scanner;
public class Calculator {
// Compute an arithmetic expression
public static void main(String[] args) {
// Declare the identifiers
final String END = "=";
String input;
double num1 = 0;
double num2 = 0;
char operator = 0;
boolean isOperator;
Scanner scnr = new Scanner (System.in);
System.out.println("Enter your numeric expression in the following form: ");
System.out.println("number operator number operator number = ");
System.out.println("Leave a blank space after each number or operator.");
System.out.println("Example: 3.5 * 3 - 5 / 2.5 =");
// Input the first item
System.out.print("> ");
input = scnr.next();
// Process the first item and input and process the rest of the items
while (!input.equals(END)){
isOperator = true;
switch (input){
case "+":
operator = '+';
System.out.println("> Operator is: " + operator);
break;
case "-":
operator = '-';
System.out.println("> Operator is: " + operator);
break;
case "*":
operator = '*';
System.out.println("> Operator is: " + operator);
break;
case "/":
operator = '/';
System.out.println("> Operator is: " + operator);
break;
default: // a number was entered
isOperator = false;
if (num1 == 0) {
num1 = Double.parseDouble(input);
System.out.println("> Num1 is: " + num1);
}
else {
num2 = Double.parseDouble(input);
System.out.println("> Num2 is: " + num2);
}
} // end of switch
// do not compute the operation if the input is an operator and num1,num2 != 0
if (num1 != 0 && num2 != 0 && !isOperator) {
System.out.println("Num2 before calc is " + num2);
switch (operator) {
case '+':
num1 = num1 + num2;
break;
case '-':
num1 = num1 - num2;
break;
case '*':
num1 = num1 * num2;
break;
case '/':
num1 = num1 / num2;
break;
default:
}
}
input = scnr.next();
} // end of while-loop
// Display the answer
System.out.println("> Answer is: " + num1);
System.out.println("Have a nice day!");
}
}
Edit: As mentioned in the comments, the code does not treat the cases when the user inputs 0. Below, I removed the if(num1 == 0) and if (num1 != 0 && num2 != 0) conditions:
import java.util.Scanner;
public class Calculator {
// Compute an arithmetic expression
public static void main(String[] args) {
// Declare the identifiers
final String END = "=";
String input;
double result = 0;
double num = 0;
char operator = 0;
boolean isOperator;
Scanner scnr = new Scanner (System.in);
System.out.println("Enter your numeric expression in the following form: ");
System.out.println("number operator number operator number = ");
System.out.println("Leave a blank space after each number or operator.");
System.out.println("Example: 3.5 * 3 - 5 / 2.5 =");
// Input the first item
System.out.print("> ");
input = scnr.next();
// Process the first item and input and process the rest of the items
while (!input.equals(END)){
isOperator = true;
switch (input){
case "+":
operator = '+';
System.out.println("> Operator is: " + operator);
break;
case "-":
operator = '-';
System.out.println("> Operator is: " + operator);
break;
case "*":
operator = '*';
System.out.println("> Operator is: " + operator);
break;
case "/":
operator = '/';
System.out.println("> Operator is: " + operator);
break;
default: // a number was entered
isOperator = false;
num = Double.parseDouble(input);
System.out.println("> Num is: " + num);
} // end of switch
// do not compute the operation if the input is an operator
if (!isOperator) {
System.out.println("Result before calc is " + result);
switch (operator) {
case '+':
result += num;
break;
case '-':
result -= num;
break;
case '*':
result *= num;
break;
case '/':
result /= num;
break;
default:
result += num;
}
}
input = scnr.next();
} // end of while-loop
// Display the answer
System.out.println("> Answer is: " + result);
System.out.println("Have a nice day!");
}
}
I switched up your order a little bit and reset the holding variable.
public static void main(String[] args) {
// Declare the identifiers
final String END = "=";
String input;
double num1 = 0;
double num2 = 0;
char operator = 0;
Scanner scnr = new Scanner (System.in);
System.out.println("Enter your numeric expression in the following form: ");
System.out.println("number operator number operator number = ");
System.out.println("Leave a blank space after each number or operator.");
System.out.println("Example: 3.5 * 3 - 5 / 2.5 =");
// Input the first item
System.out.print("> ");
input = scnr.next();
// Process the first item and input and process the rest of the items
while (!input.equals(END)){
switch (input){
case "+":
operator = '+';
System.out.println("> Operator is: " + operator);
break;
case "-":
operator = '-';
System.out.println("> Operator is: " + operator);
break;
case "*":
operator = '*';
System.out.println("> Operator is: " + operator);
break;
case "/":
operator = '/';
System.out.println("> Operator is: " + operator);
break;
default: // a number was entered
if (num1 == 0) {
num1 = Double.parseDouble(input);
System.out.println("> Num1 is: " + num1);
} else {
num2 = Double.parseDouble(input);
System.out.println("> Num2 is: " + num2);
}
} // end of switch
if (num1 != 0 && num2 != 0) {
System.out.println(String.format("Num1 : %.3f, Num2: %.3f", num1, num2));
switch (operator) {
case '+':
num1 = num1 + num2;
num2 = 0;
break;
case '-':
num1 = num1 - num2;
num2 = 0;
break;
case '*':
num1 = num1 * num2;
num2 = 0;
break;
case '/':
num1 = num1 / num2;
num2 = 0;
break;
default:
}
}
input = scnr.next();
} // end of while-loop
// Display the answer
System.out.println("> Answer is: " + num1);
}
In this calculator program when I type in any other incorrect answer for the operator such as a number or a letter instead of +, -, *, / it shows the "wrong only operators" message but even when I put in the correct operator the same message still shows up.
How can the program not show the wrong message when I type in the correct symbol.
import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
double num1, num2;
double output = 0;
char operator;
Scanner scan = new Scanner (System.in);
System.out.println("Type in first number ");
while(scan.hasNextDouble() == false)
{
System.out.println("Wrong only numbers. ");
scan.nextLine();
}
num1 = scan.nextDouble();
System.out.println("Type in the operator ");
do
{
operator = scan.next().charAt(0);
System.out.println("Wrong only operators. ");
scan.nextLine();
}
while(operator != '+' && operator != '-' && operator != '*' && operator != '/');
System.out.println("Type in second number ");
while(scan.hasNextDouble() == false)
{
System.out.println("Wrong only numbers. ");
scan.nextLine();
}
num2 = scan.nextDouble();
switch (operator)
{
case '+': output = num1 + num2; break;
case '-': output = num1 - num2; break;
case '*': output = num1 * num2; break;
case '/': output = num1 / num2; break;
}
System.out.println("" + num1 + " " + operator + " " + num2 + " = " + output);
}
}
In your case it is better to use a while loop instead of a do while.
Since you are using a do while loop : that statement is being executed at least once, not matter whether the operator is correct or not.
You can add a condition there to stop it from executing but a better way is to use while loop
import java.util.Scanner;
class Main {
public static void main(String[] args)
{
double num1, num2;
double output = 0;
char operator;
Scanner scan = new Scanner(System.in);
System.out.println("Type in first number ");
while(scan.hasNextDouble() == false)
{
System.out.println("Wrong only numbers. ");
scan.nextLine();
}
num1 = scan.nextDouble();
System.out.println("Type in the operator ");
operator = scan.next().charAt(0);
while(operator != '+' && operator != '-' && operator != '*' && operator != '/')
{
System.out.println("Wrong only operators. ");
operator = scan.next().charAt(0);
scan.nextLine();
}
System.out.println("Type in second number ");
while(scan.hasNextDouble() == false)
{
System.out.println("Wrong only numbers. ");
scan.nextLine();
}
num2 = scan.nextDouble();
switch (operator)
{
case '+': output = num1 + num2; break;
case '-': output = num1 - num2; break;
case '*': output = num1 * num2; break;
case '/': output = num1 / num2; break;
}
System.out.println("" + num1 + " " + operator + " " + num2 + " = " + output);
}
}
This is a simple calculator that I need to get functioning with basic commands. The goal of this project is to program exceptions (very easy) but, I for the life of me, can not figure this out. I have looked everywhere.
Whether it's an if/else statement or a Switch/Case statement, the thrid statement always get skipped. When a user inputs "m" it is supposed to save the value of the calculation to a placeholder variable to be able to be recalled (Again, super simple). I added a default case statement to the addition section and added my save method to the default statement and it works perfectly. Every other command (r for recall, c for clear, and e for exit) also work great. m for save does not at all.....
import java.util.Scanner;
public class Calculator {
public static Scanner input = new Scanner(System.in);
public static double placeHolder;
public static void clear() {
System.out.println("Save has been deleted, Screen has been cleared.");
}
public static void end() {
System.out.println("Program ended..");
input.close();
System.exit(0);
}
public static void save(double initValue) {
System.out.println("Number saved!");
placeHolder = initValue;
}
public static void recall() {
if (placeHolder != 0){
System.out.println("Memory Place Holder Set To: " + placeHolder);
}
else {
System.out.println("There is no data saved.");
}
}
public static void commands() {
System.out.println("e = end | c = clear | m = save | r = recall | o = continue");
String command = input.nextLine();
if (command.equals("e")){
end();
}
else if (command.equals("c")){
clear();
}
else if (command.equals("r")){
recall();
}
}
public static void main(String[] args) {
boolean loop = true;
while (loop == true){
commands();
System.out.println("Please enter what you would like to do: (+,-,*,/,%)");
String function = input.nextLine();
System.out.println("Enter the first number to be calucalted (If dividing, this is the numerator):");
double n1 = input.nextDouble();
System.out.println("Enter the second number to be calucalted (If dividing, this is the denominator):");
double n2 = input.nextDouble();
//=======================
// Addition
//=======================
if (function.equals("+")){
double sum = n1+n2;
System.out.println(n1+"+"+ n2 +" = " + sum);
System.out.println("e = end | c = clear | m = save | r = recall");
String command = input.nextLine();
input.nextLine();
switch (command){
case "e":
end();
break;
case "c":
clear();
break;
case "m":
save(sum);
break;
case "r":
recall();
break;
default:
System.out.println("Default");
save(sum);
break;
}
}
//=======================
// Subtraction
//=======================
else if (function.equals("-")){
double sum = n1-n2;
System.out.println(n1 + "-" + n2 +" = " + sum);
System.out.println("e = end | c = clear | m = save | r = recall");
String command = input.nextLine();
input.nextLine();
switch (command){
case "e":
end();
case "c":
clear();
case "m":
save(sum);
case "r":
recall();
}
}
//=======================
// Multiplication
//=======================
else if (function.equals("*")){
double sum = n1*n2;
System.out.println(n1 + "*" + n2 +" = " + sum);
System.out.println("e = end | c = clear | m = save | r = recall");
String command = input.nextLine();
input.nextLine();
switch (command){
case "e":
end();
case "c":
clear();
case "m":
save(sum);
case "r":
recall();
}
}
//=======================
// Division
//=======================
else if (function.equals("/")){
double sum = n1/n2;
System.out.println(n1 + "/" + n2 +" = " + sum);
System.out.println("e = end | c = clear | m = save | r = recall");
String command = input.nextLine();
input.nextLine();
switch (command){
case "e":
end();
case "c":
clear();
case "m":
save(sum);
case "r":
recall();
}
}
//=======================
// Mod
//=======================
else if (function.equals("%")){
double sum = n1%n2;
System.out.println(n1 + "%" + n2 +" = " + sum);
System.out.println("e = end | c = clear | m = save | r = recall");
String command = input.nextLine();
input.nextLine();
switch (command){
case "e":
end();
case "c":
clear();
case "m":
save(sum);
case "r":
recall();
}
}
}
//=======================
// Dictate loop duration:
//=======================
System.out.println("Would you like to continue? (Y|N): ");
String ans = input.nextLine();
if (ans.equals("N") || ans.equals("n")){
System.out.println("Closing Program");
loop = false;
end();
}
}
}
The main code in question is this: I know the rest don't have a default or break statement. This one does and I am debugging and trying to figure out why the m fails. Right now if you him m, it just goes to the default case statement which, does not solve the issue.
switch (command){
case "e":
end();
break;
case "c":
clear();
break;
case "m":
save(sum);
break;
case "r":
recall();
break;
default:
System.out.println("Default");
save(sum);
break;
=========================================================================
Here is the Fix for anyone looking at this post after the fact:
public static void main(String[] args) {
boolean loop = true;
while (loop == true){
commands();
System.out.println("Please enter what you would like to do: (+,-,*,/,%)");
String function = input.nextLine();
System.out.println("Enter the first number to be calucalted (If dividing, this is the numerator):");
double n1 = input.nextDouble();
input.nextLine();
System.out.println("Enter the second number to be calucalted (If dividing, this is the denominator):");
double n2 = input.nextDouble();
input.nextLine();
//=======================
// Addition
//=======================
if (function.equals("+")){
double sum = n1+n2;
System.out.println(n1+"+"+ n2 +" = " + sum);
System.out.println("e = end | c = clear | m = save | r = recall");
String command = input.nextLine();
switch (command){
case "e":
end();
break;
case "c":
clear();
break;
case "m":
save(sum);
break;
case "r":
recall();
break;
}
}
after every input.nextDouble(); you need to call input.nextLine(); to consume the new line, see Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
remove the unnecessary input.nextLine(); after every String command = input.nextLine();
The nextDouble() does not consume the new line. You can fix this by parsing the full line and then use Double.parseDouble() to get the double value from the line like this
....
System.out.println("Enter the first number to be"+
"calculated (If dividing, this is the numerator):");
double n1 = Double.parseDouble(input.nextLine());
System.out.println("Enter the second number to be" +
"calculated (If dividing, this is the denominator):");
double n2 = Double.parseDouble(input.nextLine());
if (function.equals("+")) {
double sum = n1 + n2;
System.out.println(n1 + "+" + n2 + " = " + sum);
System.out.println("e = end | c = clear | m = save | r = recall");
String command = input.nextLine();
switch (command) {
case "e":
end();
break;
case "c":
clear();
break;
case "m":
save(sum);
break;
case "r":
recall();
break;
}
....
Note
You do not have to check while(loop == true) with boolean variables you can just do check by doing while(loop).
Check this Complete code link
There are few things you need to take care of.
Have a good exception handling.
Validate the user inputs
Changes I made to your code-
clear the placeHolder value in clear() method
using input.next() inplace of input.nextLine() and removing extra input.newLine() methods
added break statements to all switch statements
You need to modularize a lot of things in your code. Have a look at Best Coding practice
input.nextDouble() reads the numbers, but does nothing with the end-of-line. So when you do this later in the code:
String command = input.nextLine();
it handles the left-over end of line, not the "m" you type next.
To fix, do something to handle the end of line on your input, such as adding input.nextLine() after calling nextDouble():
double n1 = input.nextDouble();
input.nextLine();
double n2 = input.nextDouble();
input.nextLine();
I made a Java calculator, but when I enter a number that's really long, I get this error:
Exception in thread "main" java.util.InputMismatchException: For input string: "77777777777777777777777"
at java.util.Scanner.nextInt(Scanner.java:2123)
at java.util.Scanner.nextInt(Scanner.java:2076)
at question1.Question1.main(Question1.java:26)
Here's my coding:
package question1;
import java.util.Scanner;
public class Question1 {
public static void main(String[] args) {int n1, n2;
String operation;
Scanner scannerObject = new Scanner(System.in);
System.out.println("Please enter first number.");
n1 = scannerObject.nextInt();
Scanner op = new Scanner(System.in);
System.out.println("Please enter your operation.");
operation = op.next();
System.out.println("Please enter second number.");
n2 = scannerObject.nextInt();
switch (operation) {
case "+":
System.out.println("Your result is " + (n1 + n2));
break;
case "-":
System.out.println("Your result is " + (n1 - n2));
break;
case "/":
System.out.println("Your result is " + (n1 / n2));
break;
case "*":
System.out.println("Your result is " + (n1 * n2));
break;
default:
System.out.println("Could not compute. Please only enter integers.");
}
}
}
Thanks. :)
The number 77777777777777777777777 (23 digits) is too long to fit in an int, because the maximum int possible is about 2 billion (10 digits). It's also too long to fit in a long, whose maximum value is 19 digits.
Either include an error message stating that the number is too big, or switch your datatype to BigInteger, by using Scanner's nextBigInteger method.
I need to write an application which lets the user put in two values and an operator and then calculate it. If the operator is different form +,-,/ or * the application should prompt "Wrong operator input". When it's compiled it should run something like this:
Give me number 1: 5
Give me number 2: 2
Give me an operator: +
Result: 7
The text in bold is userinput.
So far... I've got nothing. I mean I have this:
import java.util.Scanner;
public class test2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n1;
int n2;
String o;
System.out.print("Give me number 1: ");
n1 = input.nextInt();
System.out.print("Give me number 2: ");
n2 = input.nextInt();
System.out.print("Give me an operator: ");
o = input.nextLine();
}
}
But that's about it. I have no idea how to proceed. The biggest question I have is: How do I get the users operator to be an actual operator?
Possibly something like the below would suit your needs:
Scanner input = new Scanner(System.in);
System.out.print("Give me number 1: ");
int n1 = input.nextInt();
System.out.print("Give me number 2: ");
int n2 = input.nextInt();
System.out.print("Give me an operator: ");
String o = input.next();
switch (o) {
case "+":
System.out.println(n1 + n2);
break;
case "-":
System.out.println(n1 - n2);
break;
case "*":
System.out.println(n1 * n2);
break;
case "/":
System.out.println(n1 / n2);
break;
default:
System.out.println("Error, invalid operand.");