0

我的代码:

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但计算器没有重新启动。

解决方案

那是我不知道的,希望通过在这里发布来知道。

4

6 回答 6

6

利用

if ( "yes".equalsIgnoreCase(t))

代替

  if ( t == "yes")

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

阅读相关文章以了解您的理解:

Java String.equals 与 ==

于 2013-06-27T08:26:26.850 回答
6

不正确String的比较,而不是:

if ( t == "yes"){

你应该有

if ("yes".equalsIgnoreCase(t)) {
于 2013-06-27T08:26:27.837 回答
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);
}
}
于 2013-06-27T09:07:48.833 回答
1

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

answer="yes".equalsIgnoreCase(t);

替换代码:

    if ( t == "yes"){
       answer = true;
    }else{ 
        answer= false;
    }
于 2013-06-27T08:30:17.127 回答
1

纠正这个:

if ( "yes".equalsIgnoreCase(t))

而不是

  if ( t == "yes")

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

于 2013-06-27T08:38:58.237 回答
1

使用equals()而不是==比较Strings。

"yes".equals(t)

阅读此线程以获取更多信息

于 2013-06-27T08:27:39.033 回答