字符串比较问题

时间:2013-06-27 08:25:24

标签: java

我的代码:

import java.io.*;
public class compute_volume
{
   public static void main(String args[])throws IOException{
       InputStreamReader reader = new InputStreamReader(System.in);
       BufferedReader input = new BufferedReader(reader);
       boolean answer;
       double radius,height;
       final double pi = 3.14159;
       do{System.out.println("Enter the radius,press enter and then enter the height");
       String t = input.readLine();
       radius = Integer.parseInt(t);
       t = input.readLine();
       height = Integer.parseInt(t);
       System.out.println("The volume of a cylinder with radius " + radius + " and height " + height + " is " + (pi*pi*height) + "\n Thanks for using my cylinder volume calculator.Enter \"yes\" to use again or \"no\" to stop.");
       t = input.readLine();
       System.out.println(t);
       if ( t == "yes"){
           answer = true;
        }else{ 
            answer= false;
        }
    }while(answer);
    }
}

问题

用户输入yes但计算器不会重新启动。

解决方案

这是我不知道的,并希望通过在此处发布来了解。

6 个答案:

答案 0 :(得分:6)

使用

if ( "yes".equalsIgnoreCase(t))

而不是

  if ( t == "yes")

equals方法检查字符串的内容,而==检查对象是否相等。

阅读相关文章以便您理解:

Java String.equals versus ==

答案 1 :(得分:6)

String比较不正确,而不是:

if ( t == "yes"){
你应该

if ("yes".equalsIgnoreCase(t)) {

答案 2 :(得分:1)

使用equals()代替==来比较String

"yes".equals(t)

Read this thread for more information

答案 3 :(得分:1)

在Java中,对于String,请记住使用“equals()”而不是“==”。

answer="yes".equalsIgnoreCase(t);

替换代码:

    if ( t == "yes"){
       answer = true;
    }else{ 
        answer= false;
    }

答案 4 :(得分:1)

纠正这个:

if ( "yes".equalsIgnoreCase(t))

而不是

  if ( t == "yes")

如果我们不重写Equals(),则默认调用Object类的Equals()。因此它将比较内容而不是对象。

答案 5 :(得分:1)

最好使用如下

 import java.io.*;
 import java.util.Scanner;

 public class compute_volume {
    public static void main(String args[])throws IOException{
    Scanner sc = new Scanner(System.in);
    boolean answer;
    double radius,height;
    final double pi = 3.14159;
    do{System.out.println("Enter the radius,press enter and then enter the height");
        String t = sc.nextLine();
        radius = Double.parseDouble(t);
        t = sc.nextLine();
        height = Double.parseDouble(t);
        System.out.println("The volume of a cylinder with radius " + radius + " and height " + height + " is " + (pi*pi*height) + "\n Thanks for using my cylinder volume calculator.Enter \"yes\" to use again or \"no\" to stop.");
        t = sc.nextLine();
        System.out.println(t);
        if (t.equalsIgnoreCase("yes")){
            answer = true;
        }else{
            answer= false;
        }
    }while(answer);
}
}