为什么我的if语句与我告诉它做Java相反

时间:2014-04-17 03:10:01

标签: java string if-statement

import java.util.Scanner;

   class Lev {                                          //main class


public static void main(String args[]){
    Scanner read = new Scanner(System.in);



    Calculator obj1 = new Calculator();
    Per obj2 = new Per();
    String des;
    System.out.print("Enter your choice= ");
    des = read.nextLine();

    if(des=="calc" || des=="calculator"){

        obj1.calcultr();   

    }

    if(des=="per" || des=="percentage")
    {

        obj2.percentage();  
    }

    else
    {
        System.out.println("Argument not understood");

    }


    read.close();


  }

 }              //main class ends




import java.util.Scanner;                       //2nd class

public class Calculator {


Scanner inp = new Scanner(System.in);

public void calcultr(){

    double num1,num2,strge = 0;
    char q;
    System.out.println("Enter 2 numbers to continue");
    System.out.print("Num1= ");
    num1 = inp.nextDouble();
    System.out.print("Num2= ");
    num2 = inp.nextDouble();
    System.out.print("Enter what do you want to do= ");
    q = inp.next().charAt(0);


        if(q=='+'){

            strge = num1+num2;
            System.out.print("Result= " + strge);
        };

        if(q=='-'){

            strge = num1 - num2;
            System.out.print("Result= " + strge);
        }

        if(q=='*'){

            strge = num1 * num2;
            System.out.print("Result= " + strge);
        }

        if(q=='/')
        {

            strge = num1/num2;
            System.out.print("Result= " + strge);
        }





}


}



import java.util.Scanner;               //3rd class



public class Per {

Scanner inp = new Scanner(System.in);

public void percentage(){

    double numa,from,per;

    System.out.println("Enter total number attained= ");
    System.out.print("Number Attained= ");
    numa = inp.nextDouble();
    System.out.print("Enter total marks from which marks attained= ");
    from = inp.nextDouble();
    per = (numa/from)*100;
    System.out.print("Percentage Achieved= " + per);

}

}

2 个答案:

答案 0 :(得分:1)

要比较字符串,请使用equals代替==

只是示例:

if(des.equals("calc") || des.equals("calculator"))

而不是

if(des=="calc" || des=="calculator")

简而言之,

使用==:您想知道两个引用是否属于同一个对象。

使用equals:比较相等的值。

答案 1 :(得分:1)

“伙计们工作得非常感谢,但最终还是会在程序终止时出现”

您使用两个不同的if语句,第二个if语句有一个else块。我相信你要做的就是这个

if(des.equals("calc") || des.equals("calculator")){

    obj1.calcultr();   

}

else if(des.equals("per") || des.equals("percentage"))
{

    obj2.percentage();  
}

else
{
    System.out.println("Argument not understood");

}

这可以解决您在程序结束时仍然打印出来的问题。根据你的逻辑,你说如果你选择calc它cals calcultr(),但之后就说你是否选择了per,如果你已经选择了calc,那么它打印出else语句。 (如果这是有道理的,如果不是,我可以尝试更好地解释它。)