[英]I am Not able to assign the correct value of boolean result found in the program , to a boolean variable and to check a condition with the result
我在 log.d 時接收到的值為 true,但是當我將值分配給 boolean 變量時,它變為 false,而且我無法使用該值執行 if 條件,因為它也顯示為 false。 那就是我只能在日志中將值設為真,不知道如何將值傳遞給變量或檢查某些條件。 此代碼用於驗證電話號碼。
Log.d("testi3", "id " + edit_number.getText());
if (number.isEmpty()) {
Log.d("testi3", "id empty" + edit_number.getText());
edit_number.setError(getResources().getString(R.string.phone_error));
isPhoneValid = false;
} else {
Log.d("testi3", "id else " + edit_number.getText());
Pattern ptrn = Pattern.compile("[7-9][0-9]{9}");
Matcher match = ptrn.matcher(number);
Log.d("testi3", "id else 1 " + (match.find() && match.group().equals(number)));
isPhoneValid = (match.find() && match.group().equals(number));
Log.d("testi3", "id else validi" + isPhoneValid);
if ((match.find() && match.group().equals(number))) {
Log.d("testi3", "id else 2 " + (match.find() && match.group().equals(number)));
isPhoneValid = true;
} else {
Log.d("testi3", "id else 3 " + (match.find() && match.group().equals(number)));
edit_number.setError(getResources().getString(R.string.phone_error));
isPhoneValid = false;
}
}
這是輸入數字作為輸入的 logcat
D/testi3: id 9048857563
D/testi3: id else 9048857563
D/testi3: id else 1 true
D/testi3: id else validi false
D/testi3: id else 3 false
通過調用模式的matcher方法從模式創建匹配器。 創建后,匹配器可用於執行三種不同類型的匹配操作:
這些方法中的每一個都返回一個指示成功或失敗的 boolean。 更多關於匹配成功的信息可以通過查詢匹配器的state獲得。
匹配- 嘗試將整個區域與模式匹配。 如果匹配成功,則可以通過 start、end 和 group 方法獲取更多信息。
在您的場景中,當您第一次使用(match.find() && match.group().equals(number)))
匹配模式時 - 匹配成功並更新matcher
中的值,更具體地說matchFound
和group
值已更新。 下次使用相同的匹配器組比較值不滿足條件,因此導致錯誤。
您可以使用match.matches()
來檢查匹配是否成功,以便下次使用匹配而不是再次比較。
或者您可以使用reset()
方法重置匹配器
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.