简体   繁体   中英

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

}
}

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

而不是==您应该使用equals方法

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM