所以我寫了這個程序,但由於某種原因,我的else語句不起作用。 如果我輸入「e」例如我的程序會簡單地崩潰......當它實際上應該返回「無效輸入」 有人可以幫我嗎?程序將無法正常運行
============================================== ===========================
import java.util.Scanner;
public class AbsValue2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number:");
String num = input.nextLine();
Double num2 = new Double(Double.parseDouble(num));
Double abs_val = new Double(Math.sqrt(num2 * num2));
if (num.matches("[+-]?[\\d]+[.]*"))
System.out.println("The absolute value of " + num + " is |" + abs_val + "|");
else if (num.matches("[+-]?[\\d]*.[\\d]+"))
System.out.println("The absolute value of " + num + " is |" + abs_val + "|");
else
System.out.println("Invalid input");
}
}
你正試圖解析它,然後檢查它是否有效。 – khelwood
簡單的解決方法是在try和catch中打包,並在你的catch輸出無效輸入! – ApolloSoftware