Perp
Perp

Reputation: 403

how to scan for certain character with scanner(system.in)

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();

}
}

Upvotes: 2

Views: 854

Answers (3)

Gershon Papi
Gershon Papi

Reputation: 5106

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.

Upvotes: 1

Matthew Chrobak
Matthew Chrobak

Reputation: 404

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("+")

Upvotes: 3

Siva Kumar
Siva Kumar

Reputation: 2006

instead of == you should use equals method

Upvotes: 1

Related Questions