This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I am working on a VERY simple calculator with Java and it does not seem to output an answer after selecting the operation. The code is as follows:
import java.util.Scanner;
public class Calc {
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
Double fnum;
Double snum;
Double answer;
String operation;
System.out.println("Enter a number.");
fnum = keyboard.nextDouble();
System.out.println("Enter another number.");
snum = keyboard.nextDouble();
System.out.println("What operation do you wish for? [Multiplication, Addition, Subtraction, Division]");
operation = keyboard.next();
if (operation == "Multiplication" || operation == "multiplication" || operation == "*") {
answer = fnum * snum;
System.out.print("Your answer is: " + answer);
}
else if (operation == "Division" || operation == "division" || operation == "/") {
answer = fnum / snum;
System.out.print("Your answer is: " + answer);
}
else if (operation == "Addition" || operation == "addition" || operation == "+" || operation == "add") {
answer = fnum + snum;
System.out.print("Your answer is: " + answer);
}
else if (operation == "Subtraction" || operation == "subraction" || operation == "-" || operation == "subtract"){
answer = fnum - snum;
System.out.print("Your answer is: " + answer);
}
else {
System.out.println("This is not valid.");
}
}
}
and this is the output:
Enter a number.
6
Enter another number.
6
What operation do you wish for? [Multiplication, Addition, Subtraction, Division]
Multiplication
This is not valid.
Any help would be very appreciated.
P.S. there are no errors.
Thanks!
There are 2 problems. A problem with Scanner and with the condition
keyboard.nextDouble(), keyboard.next() etc... (all except .nextLine() ) leave the newline ( \n or Enter ) in the buffer. This can cause problems etc..
I suggest adding a delimiter using keyboard.useDelimiter("\n");. This only needs to be done once and can be done right after initialization of keyboard.
That way, it will only see the Enter as a signal to end that current input.
Also, the conditions must all be using the .equals() method or .equalsIgnoreCase() which is written as:
operation.equals("Multiplication");
or
operation.equalsIgnoreCase("multiplication");
Strings should be compared via .eqauals() method. So put in the if clause operation.equals("Multiplication")...and so on...
You are comparing strings by reference, not by their values. Use .equals() instead!
As #Sebastian said you should use equals instead of ==
You can improve it a little bit to avoid the spaces mistakes or case (upper case or lower case) issues by doing it the following way:
if (operation.trim().toUpperCase().equals("MULTIPLICATION") || operation.trim().equals("*"))
That way it will work for Multiplication multiplication but also MulTIpliCation, etc.
You can get the same result using equalsIgnoreCase also
Related
This is my first try on Java. The project is a calculator that takes a number, an operator signal (+,-,*,/), and another number to create an equation and give the final value of it, asking after that if the user wants to restart the program for another equation or not. I would like to know if there is anything that I can do to improve my code.
Thanks!
/*
Name: Felipe de Araujo
Project #: 1
*/
import java.util.Scanner; //Importing API.
public class Calculator {
public static void main(String[] args){
int a = 1; //Creating variable for the first while loop.
System.out.println("Welcome to the calculator!"); //Program introduction.
while (a == 1){
Scanner input = new Scanner(System.in); //Creating the input.
double firstNumber, secondNumber, result; char operator; //Creating all variables.
//Program asking for the first number.
System.out.print("First Number: ");
firstNumber = input.nextDouble();
//Program asking for the operator
System.out.print(firstNumber + " (+,-,*,/): ");
operator = input.next(".").charAt(0);
int repeat = 1; //Creating variable for the next while loop.
//Evaluating the operator to determine if it is inside the criteria (+,-,*,/).
if (operator == '+' || operator == '-' || operator == '*' || operator == '/'){
System.out.print(firstNumber + " " + operator + " Second Number: "); //If the operator is inside the criteria than start
//asking for the second number.
}
else { //If the operator is not inside the criteria run the loop until the user type something that is.
while (repeat == 1){
System.out.print(operator + " not recognized, please select between (+,-,*,/): ");
operator = input.next(".").charAt(0);
if (operator == '+' || operator == '-' || operator == '*' || operator == '/') {
System.out.print(firstNumber + " " + operator + " Second Number: ");
repeat++;
}
}
}
secondNumber = input.nextDouble(); //Initialize the secondNumber variable to the number typed.
//Equalling the variable result to the return given by the method calculatorMethod, with the variables given.
result = calculatorMethod(firstNumber, secondNumber, operator);
System.out.println(firstNumber + " " + operator + " " + secondNumber + " = " + result);//Printing the equation.
System.out.println(" ");
// Asking the user to continue the program for another operation.
char out;//Creating the variable out.
System.out.print("[y/Y] - continue | [n/N] or any other to end program: ");
out = input.next(".").charAt(0);//Initializing the variable out to what was typed.
//Verifying if the user wants to continue the program.
if (out == 'y' || out == 'Y'){
System.out.println(" ");
}
else {//If the users type anything besides y/Y the program will exit the main loop, ending the program.
System.out.println("Bye!");
a++;
}
}
}
//Declaring the calculatorMethod and all its behaviors.
private static double calculatorMethod(double a, double b, char c){
if (c == '+'){
return a + b;
}
else if (c == '-'){
return a - b;
}
else if (c == '*'){
return a * b;
}
else {
return a / b;
}
}
}
hello and welcome to the Java world :) . Some tips :
Try to give clear name to your variables. 'a', 'b', 'c' could be complicated to understand.
Favor short methods to improve the readability of your code. For example you can create an other method which return an object of : separator + the two numbers and an other one which print the result.
You can use switch(variable) in your calculatorMethod method. For example :
switch (c) { // you have to change the name of all the variables 'c', 'a' and 'b'
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
default:
return a / b;
}
}
You can create an enum or a list with the different operators.
When you check the input operator, you can use a while() loop and delete the if...else loop. The condition of the while loop could be "while the operator is not the correct one (and so, not contained in the list of correct operators), loop again and again".
The scanner initialization Scanner input = new Scanner(System.in); should be out the while() loop because you need to initialize only one time the scanner and in this case, you initialize X times (X refers to the numbers of loops).
Good luck :)
I'm writing a simple program with a do while loop and switch, which cna accept a mathematical operation and execute it for given 2 numbers.
The problem I have is, why should I initialize the result produced by the operation to zero at the beginning.
If I don't make ans=0, it gives me errors. If the given conditions are not met, some code parts are not executed and I don't need "ans".
package q3;
import java.util.Scanner;
public class Q3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char operator;
float no1, no2, ans=0; // <-------------- Why should I initialize ans
do {
System.out.println(" Mathematical Operations to be performed :");
System.out.println("\t * Multiplication\n\t / Division\n\t + Addition\n\t - Subtraction");
System.out.println("Press any other character to exit");
System.out.print("Mathematical Operator : ");
operator = input.next().charAt(0);
if (operator == '*' || operator == '/' || operator == '+' || operator == '-') {
System.out.print("Number 1: ");
no1 = input.nextFloat();
System.out.print("Number 2: ");
no2 = input.nextFloat();
switch (operator) {
case '*':
ans = no1 * no2;
break;
case '/':
ans = no1 / no2;
break;
case '+':
ans = no1 + no2;
break;
case '-':
ans = no1 - no2;
break;
}
System.out.println("The answer of " + no1 + operator + no2 + " = " + ans);
}
} while (operator == '*' || operator == '/' || operator == '+' || operator == '-');
}
}
Java requires that all local variables are initialised before they are used.
In your print line, you read the value of abs, but not all control paths set a value to it. (Even though you think you've covered all possibilities of your switch given the outer if, the compiler will not see things that way: some other thread could modify operator).
So your IDE / compiler is suggesting that you initialise it at the point of declaration.
This is because if no case evaluates to true, the value of ans will not be set. So you cannot use it.
You can overcome this by adding a default case, and setting the value of ans as 0 in that.
You should initialize ans=0; because you didn't have a default value for ans, for this you need to initialized it.
But if you add the defualt value you don't need to initialize it like this:
...
case '-':
ans = no1 - no2;
break;
default :
ans = someValue;
break;
Well, it could be that none of the case statements apply and as a result ans would still be un-initialized. And since local variables have to be initialised before they are being used, you get this error.
If you didnt initialize it, you ans will have a garbage value at first.
It is not compulsory to initialize it.
But your program will be a better program if you initialize it.
I'm new to java programming. I tried to make calculator that can do 4 basic math operations using if statement. However I don't have it working as expected. When trying to parse operator, it just finishes with else statement.
I guess I have not properly formatted if statement ?
Any help is greatly appreciated.
Thanks.
import java.util.Scanner;
import java.lang.Object;
public class calc {
public static void main(String args[]) {
System.out.println("Test kalkulator za sabiranje");
Scanner keyboard = new Scanner(System.in);
double fnum, snum, res;
String ch = "";
System.out.println("Enter first number: ");
fnum = keyboard.nextDouble();
System.out.println("Enter operation: ");
ch = keyboard.next();
if( ch == "+") {
System.out.println("Enter second number: ");
snum = keyboard.nextDouble();
res = fnum + snum;
System.out.println("Result is: "+ res);
}
else if ( ch == "-") {
System.out.println("Enter second number: ");
snum = keyboard.nextDouble();
res = fnum - snum;
System.out.println("Result is: "+ res);
}
else if ( ch == "/") {
System.out.println("Enter second number: ");
snum = keyboard.nextDouble();
res = fnum / snum;
System.out.println("Result is: "+ res);
}
else if( ch == "*") {
System.out.println("Enter second number: ");
snum = keyboard.nextDouble();
res = fnum * snum;
System.out.println("Result is: "+ res);
}
else {
System.out.println("You entered wrong operator, please try again");
}
keyboard.close();
}
}
String objects are reference objects, meaning when you type out code like
str == "+"
you're checking to see if the point in memory where str is located is equal to +. To verify if two strings equate each other, you need to use the method .equals like so
str.equals("+")
instead of == you should use equals method
Your code is fine, the problem is when you compare ch with the strings "+","-", and so on...
In java strings are Objects. Comparing objects with the == operator would only return true if the objects referrring to the same object. In order to actually compare the two objects you need to use the equals() method.
So to sum up, the correct conditions should be:
if(ch.equals("+")){ }
for every comparison.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I'm trying to figure out why my function isn't working as it should. The code is fairly basic and self explanatory. Here is the function:
public static void Greet(){
System.out.println("Hello, what is your name? ");
name = scan.nextLine();
do{
System.out.println("Would you like to order some coffee, " + name + "? (y/n) ");
input = scan.nextLine();
if(input == "y"){
System.out.println("Great! Let's get started.");
break;
}
else if(input == "n"){
System.out.println("Come back next time, " + name + ".");
System.exit(0);
}
else{
System.out.println("Invalid response. Try again.");
}
}
while(true);
}
Basically, regardless of what I enter as "input" on line 5, the function will treat it as if I hadn't entered a 'y' or 'n', it just constantly loops the while(true) and printing "Invalid response. Try again." I have no idea why my if/else statements aren't working correctly. Any help would be appreciated, thanks!
Compare String by equals not by ==
if((input.trim()).equals("y")){
equals compares the value
== comapres the reference
Compare with equals.
if(input.equals("y")){
System.out.println("Great! Let's get started.");
break;
}
else if(input.equals("n")){
System.out.println("Come back next time, " + name + ".");
System.exit(0);
}
My program's not working. What do you think is wrong?
Scanner in = new Scanner(System.in);
System.out.print("Enter first number: ");
double num1 = in.nextDouble();
System.out.print("Enter second number: ");
double num2 = in.nextDouble();
System.out.println("Enter operation to perform: ");
String oper = in.next();
if(oper == "add" || oper == "addition" || oper == "+") {
double sum = num1 + num2;
System.out.printf("The sum of the two numbers is %d", sum);
}
When I type the operation(which is a String), program terminates. Output:
Enter first number: 12
Enter second number: 8
Enter operation to perform:
"add"
Process completed.
I can't seem to find the error, please help?
Never compare strings with operator == - it is rough mistake. Use equals instead:
if(oper.equals("add") || oper.equals("addition") || oper.equals("+")) {
Do not use == use the equals method :
if(oper.equals("add") || oper.equals("addition") || oper.equals("+"))
== operator is used to compare address in memory space rather than the content of the strings being compared
Don't compare Strings using ==. Always use equals():
if("add".equals( oper ) || "addition".equals( oper ) || "+".equals( oper ) ) {
// ...
}
With == you compare object references (or primitive types). Strings are objects in Java, so when you compare oper and add, both point to different objects. Thus even if they contain the same value, the comparison with == fails, because they are still different objects.
if(oper == "add" || oper == "addition" || oper == "+") {
should be
if(oper.equals("add") || oper .equals("addition") || oper.equals("+")) {
use .equals method to check if two strings are meaningfully equal, == operator just checks if two reference variables refer to the same instance.
Don't compare Strings using ==. Use equals instead.
Compare strings by using equals(..) not ==
replace
if(oper == "add" || oper == "addition" || oper == "+") {
by
if(oper.equals("add") || oper.equals("addition") || oper.equals("+")) {
== compares for same reference not same content.
Do what all the others say: use equals or even equalsIgnoreCase. (There are good explanations for this so in the other answers. Would be silly to repeat it here.)
AND type "add" without the " in the console.
Only doing both will work.
use this
if("add".equals(oper) || "addition".equals(oper) || "+".equals(oper)) {
double sum = num1 + num2;
System.out.printf("The sum of the two numbers is %d", sum);
}
In addition to using equals() or still better equalsIgnore() instead of == for strings, you also need to enter add in the command-line instead of "add".
Or else, you have to compare it as:
oper.equals("\"add\"")
Also, you seem to be from a C background. Normally in Java, one would use:
System.out.println("The sum of the two numbers is " + sum);
instead of
System.out.printf("The sum of the two numbers is %d", sum);
since %d prints integer value and not double value.