Search code examples
stringif-statementbluej

The program is in BlueJ it is not seeing any case in if else and directly going to the last else statement?


public class trigo { 

    public double conversion(String a) {

        String func="",f=a,sin="sin",cos="cos",tan="tan",cosec="cosec",cot="cot",sec="sec";
        f=f.trim();
        double p=0,z=0;
        try {
            p=Double.valueOf(f);
        } catch(Exception e) {
            func=f.substring(0,3);
            f=f.substring(3,f.length());

            try {
                p=Double.valueOf(f);
            } catch(Exception d) {
                func=func.concat("ec");
                f=f.substring(2,f.length());
                p=Double.valueOf(f);
            }
        }'problem starts here'

        if(func=="")
            z=p;
        else if(func=="sin")
            z=Math.sin(p);
        else if(func=="cos")
            z=Math.cos(p);
        else if(func.=="tan")
            z=Math.tan(p);
        else if(func=="cosec")
            z=1/Math.sin(p);
        else if(func=="sec")
            z=1/Math.cos(p);
        else if(func=="cot")
            z=1/Math.tan(p);
        else
            System.out.println("please check for spelling mistake");
        'ends here'
        System.out.print(z);
    }
}

In this code its giving the output as "please check for spelling mistake"


Solution

  • func is never assigned since your entire logic was put into the catch block.

    catch(Exception e) {
                func=f.substring(0,3);
                f=f.substring(3,f.length());
    
                try {
                    p=Double.valueOf(f);
                } catch(Exception d) {
                    func=func.concat("ec");
                    f=f.substring(2,f.length());
                    p=Double.valueOf(f);
                }
            }
    

    It will run only if the input has a parsing failure.

    A simple debug (or even the println) should give you an idea what's going on.