我的代码:
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
但计算器不会重新启动。
解决方案:
这是我不知道的,并希望通过在此处发布来了解。
答案 0 :(得分:6)
使用
if ( "yes".equalsIgnoreCase(t))
而不是
if ( t == "yes")
equals方法检查字符串的内容,而==检查对象是否相等。
阅读相关文章以便您理解:
答案 1 :(得分:6)
String
比较不正确,而不是:
if ( t == "yes"){
你应该
if ("yes".equalsIgnoreCase(t)) {
答案 2 :(得分:1)
答案 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);
}
}