簡體   English   中英

檢查字符串是否為空或空 - 邏輯

[英]check string is null or empty - logic

在這篇文章的延續( 檢查字符串是 NULL 或 EMPTY ),我成功地寫出了 if 和 else 邏輯。

但是,我的第三個邏輯不起作用。 我的第三個邏輯類似於同時檢查兩個空字段,如果它們為空,則會彈出錯誤圖標。

以下是我的代碼:

    private Boolean checkEmptyField(){
    Boolean result = false;

    String subject = querySubject.getText().toString();
    String message = queryText.getText().toString();

    if(subject.isEmpty()){
        Toast.makeText(this, "Subject/Type field must not be blank!", Toast.LENGTH_SHORT).show();
        querySubjectInfoIcon.setVisibility(View.VISIBLE);
    }else if(message.isEmpty()){
        Toast.makeText(this, "Content field must not be blank!", Toast.LENGTH_SHORT).show();
        newQueryInfoIcon.setVisibility(View.VISIBLE);
    }else if(subject.isEmpty() && message.isEmpty()){
        Toast.makeText(this, "Fields are mandatory & must not be blank!", Toast.LENGTH_SHORT).show();
        newQueryInfoIcon.setVisibility(View.VISIBLE);
        querySubjectInfoIcon.setVisibility(View.VISIBLE);
    }
    else{
        result = true;
    }
    return result;
}

當我運行該應用程序並有意將兩個字段留空時,它只會檢查並在作為主題字段的一個字段上顯示圖標錯誤。 這意味着只有一個邏輯(if subject.isEmpty)正在運行。

因此,我需要一些建議如何成功運行第三個邏輯。 謝謝你。

首先對兩個條件進行測試,一旦if匹配,它將不會輸入任何else (s)。 喜歡,

if(subject.isEmpty() && message.isEmpty()) {
    Toast.makeText(this, "Fields are mandatory & must not be blank!", Toast.LENGTH_SHORT).show();
    newQueryInfoIcon.setVisibility(View.VISIBLE);
    querySubjectInfoIcon.setVisibility(View.VISIBLE);
} else if(subject.isEmpty()) {
    Toast.makeText(this, "Subject/Type field must not be blank!", Toast.LENGTH_SHORT).show();
    querySubjectInfoIcon.setVisibility(View.VISIBLE);
} else if(message.isEmpty()) {
    Toast.makeText(this, "Content field must not be blank!", Toast.LENGTH_SHORT).show();
    newQueryInfoIcon.setVisibility(View.VISIBLE);
} else {
    result = true;
}

一旦您的第一個if條件觸發,下面的else if就不會觸發。 首先在if檢查subject.isEmpty() && message.isEmpty() ,然后再檢查其他兩個條件。

  • 你可以用這個檢查它:

     if (userName != null && !userName .isEmpty() && !userName .equals("null"))
  • 你還有另一個選擇

    if (TextUtils.isEmpty(null)) { // null value return; // or break, continue, throw }else{ // string has value } Log.i("TAG", myString);

用這個

if(subjet == null){
    //blablabla
}

或者

if(message == null){
    //blablabla
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM