[英]How to write an if/else statement to check type of variable
我正在嘗試編寫一個程序,該程序從標准輸入中讀取兩個數字並查找它們是否處於黃金比例,如果輸入不是數字,則打印錯誤消息。 但是,帶有“ 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); } } }
這是因為您將A和B構造為兩倍。
if ((a == Math.floor(a)) && !Double.isInfinite(a)) {
// integer type
}
這將檢查雙精度值的四舍五入值是否與雙精度值相同。
您的變量可能具有int或double值,而Math.floor(a)
始終具有int值,因此,如果您的變量等於Math.floor(a)
則它必須具有int值。
如果變量的值是無窮大或負無窮大,那么這也不起作用,因此向條件添加“只要變量不是無窮大”。
您應該檢查給定對象是否屬於Number
,然后檢查Double
。 在下面檢查“數字”。
if (a instanceof Number && 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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.