[英]How do you get your program to print out the number of values a user has entered?
[英]How do you check that the user entered a String value instead of a number?
我編寫了一個簡單的程序,當用戶輸入A側和B側時計算三角形的斜邊。我有一個while循環,提示用戶輸入大於0的值,但是如何檢查用戶是否輸入字符串值?
while (sideA<=0 || sideB<=0)
{
我應該添加什么,以便如果用戶輸入字符串值,循環也將開始?
謝謝
但是,您首先從命令行,掃描儀或緩沖讀取器中獲取輸入,然后將其解析並嘗試將其存儲在整數變量中。 如果它是字符串,則捕獲異常並允許用戶再次輸入該值。
try
{
int sideA = Integer.parseInt(input);
}
catch (NumberFormatException ex)
{
//Do something here to keep continuing the while loop
}
Scanner input = new Scanner(System.in);
// requesting user input
System.out.println("Enter x and y : ");
String x = input.next();
String y = input.next();
try {
double d1 = Double.parseDouble(s1);
double d2 = Double.parseDouble(s2);
if(d1 > 0 && d2 > 0) {
//Call for the hypotenuse method
double z = hypotenuse(d1,d2);
}
} catch (NumberFormatException e) {
System.out.println("Invalid Input!");
}
您可以使用二進制instanceof運算符。 它以這種方式返回布爾值:
if( myVariable instanceof String )
//it's a string!
else
//it's not a string
當然,這種方法也可以用於檢查其他類型。 我建議使用instanceof將A和B變量作為字符串進行類型檢查,並進行相應處理
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.