【发布时间】:2018-01-24 00:44:56
【问题描述】:
我正在尝试编写一个程序,该程序从标准输入中读取两个数字并确定它们是否处于黄金比例,如果输入不是数字则打印错误消息。但是带有“instanceoff”的 if/else 不能正常工作,如果输入不是数字,它就会出现错误,并且即使它是,它也不是黄金比例。
谢谢
import java.util.Scanner;
public class GoldenRatio {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
System.out.print("Enter two numbers: ");
Double a = key.nextDouble();
Double b = key.nextDouble();
Double x;
Double y;
//Makes sure the bigger number becomes numerator
if(a <= b){
x= b;
y= a;
} else {
x = a;
y = b;
}
//Rounding decimal to 3 figures
Double left = (x+y)/x;
Double right = x/y;
String leftS = String.format("%.3f", left);
String rightS = String.format("%.3f", right);
Double leftD = Double.parseDouble(leftS);
Double rightD = Double.parseDouble(rightS);
// meant to make sure arguments are doubles
if (a instanceof Double && b instanceof Double) {
if (leftS == rightS) {
System.out.println("Golden ratio!");
} else {
System.out.println(leftS);
System.out.println(rightS);
System.out.println("Maybe next time");
System.exit(0);
}
}else {
System.out.println("Invalid input");
System.exit(0);
}
}
}
【问题讨论】:
-
你的代码是
Double a那你为什么需要if (a instanceof Double? -
请阅读How do I compare strings in Java? -- 并将
if (leftS == rightS)替换为if (leftS.equals(rightS))。另外a和b已经属于Double类型,因此对它们进行instanceof检查是没有意义的。 -
请勿将
Java代码发布为HML/CSS/JavaScriptsn-p... -
您的问题是捕捉输入是否为数字。我认为这一点是给出错误
-
我需要执行 instanceof,因为其中一个要求是确保输入是数字字符,例如,如果用户只是键入“foo”和“bar”,那么它意味着打印无效输入.除非我使用错误的 instanceof 并且它意味着其他东西?
标签: java if-statement instanceof