This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I don't know why this is not working I get no compilation error here but the program always returns the else statement. Am I supposed to define operation some other way or call it someway else?
import javax.swing.JOptionPane;
public class Calculator1 {
public static void main(String []Args) {
String firstNum;
String operation;
String secondNum;
firstNum = JOptionPane.showInputDialog("Input a number.");
secondNum = JOptionPane.showInputDialog("Input another number.");
double num1 = Double.parseDouble(firstNum);
double num2 = Double.parseDouble(secondNum);
operation = JOptionPane.showInputDialog("Input an operation sign.");
if (operation == "x") {
System.out.println( num1 * num2 );
}
if (operation == "*") {
System.out.println( num1 * num2 );
}
if (operation == "/") {
System.out.println( num1 / num2 );
}
if (operation == ":") {
System.out.println( num1 / num2 );
}
if (operation == "+") {
System.out.println( num1 + num2 );
}
if (operation == "-") {
System.out.println( num1 - num2 );
}
else {
System.out.println("Please enter an appropriate operation sign.");
}
}
}
The problem is with your if statements. The else statement will always execute if operation is not equal to "-". This is because each of your if statements is a separate block of code.
if(x) {}
if(y) {}
if(z) {}
else {}
You can make this work by using else if instead of several if statements.
if(x) {}
else if(y) {}
else if(z) {}
else {}
This will work, but the correct way to do this would be to use a switch statement.
switch(operation) {
case "x": result = num1 * num2 ;
break;
case "/": result = num1 / num2;
break;
case "-": result = num1 - num2;
break,
default: System.out.println(errorMessage);
}
You should use "x".equals(operation);
First, you need use if/else structure:
if (operation == "x") {
System.out.println( num1 * num2 );
}
else if (operation == "*") {
System.out.println( num1 * num2 );
}
else if (operation == "/") {
System.out.println( num1 / num2 );
}
// Continue...
Next thing, in java, you can't compare string's content with '==' operator. You should use equals method:
if (operation.equals("x")) {
System.out.println( num1 * num2 );
}
else if (operation.equals("*")) {
System.out.println( num1 * num2 );
}
else if (operation.equals("/")) {
System.out.println( num1 / num2 );
}
// Continue...
This should works, but. Why doesn't works the '==' operator?
Strings are objects in java, you handle objects with references. So when you are doing '==', you are comparing references's address. If you want compare the content, you have to use equals method.
Another option will be use a switch:
switch(operation)
{
case "+":
System.out.println(num1 + num2);
break;
case "-":
System.out.println(num1 - num2);
break;
case "/":
System.out.println(num1 / num2);
break;
case "x":
case "*":
System.out.println( num1 * num2 );
break;
default:
System.out.println("Error!");
}
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);
}
}
I recently made a calculator and everything is working fine except for the equal button. While it is outputting the right answer, I would like to keep using operator even after pressing equals. How can I do that?
if(e.getSource() == btnEquals) {
num2 = 0;
char operator2 = 's';
try {
display.append("=" + "\n");
for ( String line : display.getText().split("\\n")) {
char operator1 = line.charAt(line.length()-1);
num1 = Double.parseDouble(line.substring(0, line.length()-1));
if (operator2 == 's') {
num2 = num1;
operator2 = operator1;
} else if (operator2 == '+') {
num2 = num2 + num1;
operator2 = operator1;
} else if (operator2 == '-') {
num2 = num2 - num1;
operator2 = operator1;
} else if (operator2 == '*') {
num2 = num2 * num1;
operator2 = operator1;
} else if (operator2 == '/') {
num2 = num2 / num1;
operator2 = operator1;
}
}
} catch (NumberFormatException a) {
display.setText("Error: Consecutive Operators " + " (=) " + " or no input" + "\n");
return;
}
display.setText(display.getText() + num2);
}
}
When you press the button (I assume it is a Swing JButton) all the work is done in a specific thread of execution which is called event dispatch thread. As the name implies it is not the right thread for doing the heavy lifting, i.e. your current work. While you are using it it can't dispatch events for other GUI elements so you can't use any other elements.
So you need to put your business work into an extra thread and thus deal with concurrency in Swing. You can read about it here.
Wrap it with while(True) statement and will run till the exit.
I am experiencing trouble in the creation of my reverse polish notation calculator with my validation code. I need the calculator to accept the two shift operators (<< and >>) as part of the calculations. The following snippets of code is the validation part and also the calculation.
public static boolean isInt(String userinput) {
try {
Integer.parseInt(userinput); // Try to parse. Makes sure that the values entered are actual numbers
return true; // Boolean value to show if the equation entered is valid or not
} catch (NumberFormatException e) {
System.out.println("Please enter a valid expression!");
invalidlines++;
return false;
}
}
public static boolean isValidLine(String line) {
line = line.trim();
if (line.length() <= 4) { // Trims the lines down to 4 and ensures there is no spaces being included
return false;
} else {
String[] calcarray = new String[3];
calcarray = line.split(" ");
String operators = new String("[+\\-\\*\\/\\<<\\>>\\%\\&\\|]"); // Validator using regular expressions to check the operator used
if (isInt(calcarray[0].toString()) && isInt(calcarray[1].toString()) && calcarray[2].matches(operators)) { // Checks that the operator in the string matches the ones in the regular expression
return true;
} else {
return false;
}
}
}
below is the calculator part:
String keyboardInput = new String();
Scanner kbScan = new Scanner(System.in);
int answer = 0;
while (true) {
display("Please enter an equation");
keyboardInput = kbScan.nextLine();
if (isValidLine(keyboardInput)) {
String[] equation = new String[3]; // We know that this is only going to contain 3 to be valid
equation = keyboardInput.split(" "); // split this up, as it's stored with the spaces.
int num1 = Integer.parseInt(equation[0]);
int num2 = Integer.parseInt(equation[1]);
switch (equation[2]) { // This case switch checks the third position of the
// string to decide which operator is being used. It then works out the
// answer and breaks to the next instruction
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;
case (">>"):
answer = num1 >> num2;
break;
case ("%"):
answer = num1 % num2;
break;
case ("|"):
answer = num1 | num2;
break;
case ("&"):
answer = num1 & num2;
break;
}
display("Your post fix expression: " + equation[0] + " " + equation[1] + " " + equation[2]);
display("Your calculation: " + equation[0] + " " + equation[2] + " " + equation[1] + " = " + answer);
} else {
display("The equation you entered is invalid");
}
}
Whenever a valid expression is entered the following error is shown in the console:
Enter F for file calculator or K for keyboard input
k
Please enter an equation
10 2 <<
The equation you entered is invalid
Please enter an equation
And I cannot figure out which part of my validation is wrong for these expressions.
Problem is with your operators regex.
User rather something like:
("\\+|\\-|\\*|\\/|<<|>>|\\%|\\&|\\|")
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am trying to build a simple calculator that operates on Double values and performs:
+
-
*
/
negation
^2
for some reason, whichever operation i specify when running the program executes the addition function. So when I try to do
5
7
*
I get 12.0 and not 35.
Any suggestions?
I would also really like some help implementing a way to quit this program when the word "exit" is entered. I was thinking something like System.exit(0);
but Im not sure how to implement. this is my code so far:
import java.util.Scanner;
public class Calc {
public static void main(String[] args)
{
double num1;
double num2;
String operation;
Scanner input = new Scanner(System.in);
System.out.println ("Enter 'exit' to quit the calculator or 'help' for more options");
System.out.println("Enter the first number:");
num1 = input.nextInt();
System.out.println ("Display:" + num1);
System.out.println("Enter the second number:");
num2 = input.nextInt();
System.out.println ("Display:" + num2);
Scanner op = new Scanner(System.in);
System.out.println("Please enter operation:");
operation = op.next();
if (operation == "+");
{
System.out.println((num1 + num2));
}
if (operation == "-"){
{
System.out.println((num1 - num2));
}
if (operation == "/"){
{
System.out.println((num1 / num2));
}
if (operation == "*"){
{
System.out.println((num1 * num2));
}
}
}
there is a semicolon at if (operation.equals("+"));
so, System.out.println((num1 + num2)); will always work
And also replace, == with .equals("+")
as == checks for reference, while equals checks for the value of the variable.
please change operation == to operation.equals("your value")
There are at least three main issues with your code...
Firstly, String comparison in Java is done using .equals not ==
Secondly...
if (operation == "+");
Has a semi-colon at the end, which basically means that even if the condition is meet, it will not run anything, but will skip to the next execution block, which is ...
{
System.out.println((num1 + num2));
}
Thirdly, you have an extra open brace ({) here...
if (operation == "-"){
{
Here...
if (operation == "/"){
{
And here...
if (operation == "*"){
{
Which is going to completely screw up your logic
You should also make use of else-if blocks as well...
Instead, try something like...
if ("+".equals(operation))//;
{
System.out.println((num1 + num2));
}
else if ("-".equals(operation)) //{
{
System.out.println((num1 - num2));
}
else if ("/".equals(operation)) //{
{
System.out.println((num1 / num2));
}
else if ("*".equals(operation)) //{
{
System.out.println((num1 * num2));
}
I've commented out the problem areas so you can see where they exists before hand
try this way
Instead of using == use .equals()
import java.util.Scanner;
public class Calc {
public static void main(String[] args)
{
double num1;
double num2;
String operation;
Scanner input = new Scanner(System.in);
System.out.println ("Enter 'exit' to quit the calculator or 'help' for more options");
System.out.println("Enter the first number:");
num1 = input.nextInt();
System.out.println ("Display:" + num1);
System.out.println("Enter the second number:");
num2 = input.nextInt();
System.out.println ("Display:" + num2);
Scanner op = new Scanner(System.in);
System.out.println("Please enter operation:");
operation = op.next();
if (operation.equals("+"))
{
System.out.println((num1 + num2));
}
if (operation.equals("-"))
{
System.out.println((num1 - num2));
}
if (operation.equals("/")){
{
System.out.println((num1 / num2));
}
if (operation.equals( "*")){
{
System.out.println((num1 * num2));
}
}
}