为什么这个If语句不能用于字符串?

时间:2015-03-30 02:00:53

标签: java string math if-statement pow

import java.util.Scanner;

公共类方法{

/*
 * Compound interest Program Quarterly
 */


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

        System.out.println("What is the Rate");
        int rate = keyboard.nextInt()/100;
        System.out.println("What is the Amount");
        int amount = keyboard.nextInt();
        System.out.println("How many years?");
        int years = keyboard.nextInt();

        keyboard.nextLine();
        System.out.println("How is it compounded? Press Q = Quarterly, A = Anually, S = SemiAnnualy, M = Monthly");

        String answer = keyboard.nextLine();

       int easy = amount*(1+(rate/years));
       int pow = 4 * years;


        if (answer == "/Q"){
            System.out.println("Your answer compounded Quarterly is: "  + Math.pow(easy,pow));

这是代码,但if语句带有String ==" Q"没有工作,因为当我按Q时没有任何事情发生?问题是什么?

3 个答案:

答案 0 :(得分:0)

Java对吗?使用equalsIgnoreCase是因为你可以输入' q'那个/他们也告诉过你,记住它

答案 1 :(得分:0)

第一个问题是你在这一行中有一个拼写错误(正斜杠):

if (answer == "/Q"){

第二个问题是你不能比较这样的字符串。 而是使用" equals()"方法

if(answer.equals("Q")){

有关详细信息,请参阅此处:How do I compare strings in Java?

答案 2 :(得分:0)

也许你可以试试

if(answer.equals("Q"))