English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
في هذا البرنامج، ستتعلم كيفية استخدام جمل if-else ووظائف Java لفحص ما إذا كانت النصوص فارغة أو null.
public class Null { public static void main(String[] args) { String str1 = null; String str2 = ""; if(isNullOrEmpty(str1)) System.out.println("النص الأول هو null أو فارغ."); else System.out.println("النص الأول ليس null أو فارغ."); if(isNullOrEmpty(str2)) System.out.println("النص الثاني هو null أو فارغ."); else System.out.println("النص الثاني ليس null أو فارغ."); {} public static boolean isNullOrEmpty(String str) { if(str != null && !str.isEmpty()) return false; return true; {} {}
عند تشغيل هذا البرنامج، الناتج هو:
النص الأول هو null أو فارغ. النص الثاني هو null أو فارغ.
في البرنامج السابق، لدينا نصان str1 وstr2. str1 يحتوي على قيمة null، وstr2 هو نص فارغ.
نحن أيضًا قمنا بإنشاء دالة isNullOrEmpty()، كما تدل الاسم، تقوم بفحص ما إذا كانت النصوص null أو فارغة. تستخدم != null و طريقة isEmpty() من string للتحقق من null.
بالكلمات البسيطة، إذا كان النص ليس null ولا يعود isEmpty() false، فإنه ليس null ولا فارغ. وإلا، نعم.
لكن، إذا كان النص يحتوي فقط على حروفitespace (مسافات)، لن يعود البرنامج empty. من الناحية التقنية، يجد isEmpty() أن يحتوي على مسافات ويقوم بإرجاع false. بالنسبة للنصوص التي تحتوي على مسافات، نستخدم طريقة string trim() لقص جميع الحروفitespace المقدمة والخلفية.
public class Null { public static void main(String[] args) { String str1 = null; String str2 = " "; if(isNullOrEmpty(str1)) System.out.println("str1 هو null أو فارغ."); else System.out.println("str1 ليس null أو فارغ."); if(isNullOrEmpty(str2)) System.out.println("str2 هو null أو فارغ."); else System.out.println("str2 ليس null أو فارغ."); {} public static boolean isNullOrEmpty(String str) { if(str != null && !str.trim().isEmpty()) return false; return true; {} {}
عند تشغيل هذا البرنامج، الناتج هو:
str1 هو null أو فارغ. str2 is null or empty.
في isNullorEmpty()، قمنا بإضافة طريقة إضافية trim()، يمكنها إزالة جميع الحروفitespace في النص المحدد.
لذلك، الآن، إذا كان النص يحتوي فقط على مسافات، فإن الدالة سترجع true.