Monday, March 13, 2017

Java Enums, How to Use Them Correctly

When I learned about java enums (or enumerations), I thought that there was only one way of creating and using them in java programming language. The first time I have heard of enums was during a course called ICS 201 at KFUPM. In reality, they did not tell us about them. I just found about them while I was trying to solve problem related to showing day name in more than one language. Enums usually used to store static data that will never change through the life time of a program such as the name of days.

Before you continue with the lesson, Note that you must have the knowledge about the Following: 
  • Crating Java Files.
  • Using Main Class. 
  • Using Variables and Creating Objects.
  • Method Declaration.
  • Building Java Classes.
In this lesson we will be learning about the following:
  1. Java Enum Syntax.
  2. How to Travers All Enum Constants.
  3. Using Enum With Switch Statment.
  4. Customizing The Enum.

The Basic Syntax

There are two ways for creating enums in Java language, the easy way and the hard way. For now, let's talk about the easy way.

Suppose that a student is studying at university. The university classify students into 5 different categories, New Student, Freshman, Sophomore, Junior and Senior. We can use Java enum to store the values as follows:

public enum StudentLevel {
    NEW,FRESHMAN,SOPHOMORE,JUNIOR,SENIOR
}


This is the simplest way for creating enums in Java. The keyword 'enum' indecates that we are extending (or inherting from) the class Enum. This class is the base for all enumerated types in java language.

Now let's create new class and call it 'Student'. Inside our student class, we can have an attribute called 'level' which has the type 'StudentLevel'. We can set this attribute to any constant value that we have defined inside the "StudentLevel" enum.

public class Student {
    private StudentLevel level;
   
    public StudentLevel getLevel() {
        return this.level;
    }
   
    public void setLevel(StudentLevel level) {
        this.level = level;
    }

    public String toString(){
        return "Student Level: "+this.level;
    }
}


Finally, we create a min class to test how the code will work. We create an object of type student and set the level as follows:

public class Main{
    public static void main(String [] arguments){
        Student s = new Student();
        s.setLevel(StudentLevel.NEW);
        System.out.println(s);
    } 
}


When we run the program in NetBeans IDE, the output will be as follows:


Traversing Enum Values 

To print the values of all the constants inside the enum, we use the enhanced 'for' loop to do that. The following code snippet shows how its done.

public class Main{
    public static void main(String [] arguments){
        for(StudentLevel level : StudentLevel.values()){
            System.out.println(level);
        }
    } 
}

The Method 'values()' return an array that contains all the constants within the given enum. This program will show the following in the console:


Using The Enum With 'Switch' Statment

Most of the time, the enums are used within switch statement. We will use the same example that we used above to illestrate how to use the enum with switch statement. Depending on the assigned value for the attribute 'level', we can do different things.

public class Main{
    public static void main(String [] arguments){
        Student s = new Student();
        s.setLevel(StudentLevel.SENIOR);
       
        switch(s.getLevel()){
            case NEW:{
                System.out.println("Welcom to the university.");
                break;
            }
           
case FRESHMAN:{
                System.
out.println("Do your best, You still have 4 more years to go");
               
break;
            }
           
case SOPHOMORE:{
                System.
out.println("Finsh this year and you will be graduated in 3 years.");
                break;
            }
           
case JUNIOR:{
                System.
out.println("Two more years left");
               
break;
            }
           
case SENIOR:{
                System.
out.println("You did work hard. This is your final year!!");
               
break;
            }
        }
    } 
}



Customizing Enums

So far, we have seen the basic use of enum. But what if we would like to add more extra information inside the enum? For example, we may need to associate a range of credit hours for each level. This can be done by creating a constructor inside the enum that accepts parameters. By default, java provide an empty constructor for the enum. Now let's modify our basic enum and create a custom constructor in addition to the attributes that we need.

What we will do is to create a constructor that accepts 3 parameters, a name of type string and two other parameters of type integer. The name is just used to change how the name of the constant appears. By default, it appears in the way we define it. For example, if the name of the constant is 'SuNdAY', it will show as 'SuNdAY' in the console. By overriding the "toString()" method, we can change this.

Also we will create methods inside the enum to access the new attributes.

public enum StudentLevel {
    NEW("New Student",0,15),
    FRESHMAN("Freshman",16,45),
    SOPHOMORE("Sophomore",46, 70),
    JUNIOR("Junior",71, 90),
    SENIOR("Senior",91,132)
    //notice the semicolon here instead of a comma
    ;
    //the keyword final is optional
    private final int minCH, maxCH;
    private final String name;
   
    private StudentLevel(String name,int minCreditHours, int maxCreditHours){
        this.name = name;
        this.minCH = minCreditHours;
        this.maxCH = maxCreditHours;
    }
   
    public int getMinCreditHours(){
        return this.minCH;
    }
   
    public int getMaxCreditHours(){
        return this.maxCH;
    }
   
    public String value(){
        return this.name;
    }
   
    public String toString(){
        return this.name+", Min Credits: "+this.minCH+", Max Credits: "+this.maxCH;
    }
}


So, what did we do to create this custom enum? We did the following:
  • Replace the default enum constructor with custom one.
  • For each constant, we have added the extra attributes as if we where calling a method.
  • To do that, we added semicolon after the last enum constant.
  • The things that come after the semicolon is similar to any java class declaration.
  • We can add methods, attributes and to any other thing inside.
Now if we loop through the constants of the enum, we will see something different from what we have seen before. The reason for that is because we created our own custom 'toString()' method.



We can even do more if we would like since we are working with the enum as class. For example, we may make our enum implement java interfaces.


Sunday, March 12, 2017

مشكلة ظهور تحذير مشكلة بالمحرك, ما هي أسبابها؟

نوع سيارتي هو هيونداي إلَنترا. قبل حوالي إسبوعين من اليوم, ظهرت لدي إشارة تحذير تفقد المُحرك.

 طبعا لقد خِفت كثيرا عِندما ظهرت لان ظهور هذا التحذير يدل على وجود مشكلة بالمحرك و يجب زيارة احد الورش لتفقد المشكلة. ما قُمت به هو سؤال بعض من اصحابي عن هذه المشكلة و قد رد علي أكثرهم بثلاثة حلول, الحل الأول هو فصل بطارية السيارة و إعادة تركيبها. الحل الثاني تغيير زيت المكينة. الحل الثالث الذهاب إلى احد الورش.

لاحظت ان الحل الأول كان مقترح من جميع اصدقائي مع انه ليس منطقي. طبعا قُمت بِتجربته ولم يحل المشكلة. الحل الثاني لم اقم بِعمله لانني قُمت بِتغيير زيت السيارة قبل فترة قصيرة. الحل الثالث قد يكون مُكلف.

بعد هذا, نسيت أمر هذا التحذير طوال الإسبوع و تذكرت أمره الإسبوع الفائت. و انا عائِد من المُحاضرة إلى السكن, قٌلت في نفسي لِماذا لا ابحث عن اسباب المشكلة باللغة الإنجليزية؟ ربما قد احصل على حلول للمشكلة. بعدها قٌمت ببحث سريع عن الأسباب المُمكنة لظهور هذا التحذير باللغة الإنجليزية. و كانت الأسباب كالتالي:

مشكلة في غِطاء خزان الوقود (خزان البنزين) 

أحد الأشياء الغير مُتوقة و اللتي تؤدي إلى ظهور هذا التحذير. عِند عدم إغلاق غِطاء خزان الوقود بِشكل مُحكم سوفَ يتسرب جزء من الوقود إلى الهواء. أيضا قد يكون هنالك شق او كسر بغطاء الخزان يؤدي إلى المشكلة. تكلُفة شراء غطاء الخزان حوالي 15 ريال سعودي. عملية تركيبه سهلة و يمكنك عملها بنفسك.

مشكلة في حساس الأُوكسجين

حساس الأوكسجين مسؤول عن تفقد مُستوى الأُوكسجين الغير محروق اللذي يخرج مِن نِظام العادم. عِندما يتعطل هذا الحساس, فإن قراءة عداد السيارة تُصبح غير دقيقة. يتعطل حساس الأوكسجين بسبب الرماد القادم من المحرك و تَجَمُع الزيت عليه. عدم إصلاح حساس الأوكسجين قد يُؤدي إلى عُطل في المُوحول الحفاز و اللذي قد يُكلف الكثير عِند إصلاحه مٌقارنة بإصلاح الحساس.

مشكلة في المحول الحفاز (الكِنداسة)

 هدف المُحول الحفاز هو التقليل مِن الغازات الضارة اللتي تخرج بسبب عملية حرق الوقود. فهو يعمل كمُفاعل مُصغر لتوحيل الغازات الضارة مثل اول اُوكسيد الكربون إلى غازات غير ضارة. أحد العلامات اللتي تدل على عطل المُحول الحفاز هي عدم قُدرة السيارة على الإنطلاق بسرعة عِند الضغط على دواسة الوقود. عِند المُحافظة على صيانة السيارة بِشكل دوري, فإن تعطل المحول الحفاز صعب. أحد اسباب تعطله هو تعطل شمعات الإحتراق او حساس الأُوكسجين. 

مشكلة في مُستشعر تدفق الهواء

مُستشعر تدفق الهواء يُخبر حاسوب السيارة بِمُعدل الهواء اللذي يأتي إلى المحرك و بالتالي يستطيع الحاسوب تحديد كمية الوقود المُناسبة لإدخالها للمحرك. عِند تعطل المُستشعر, سوف تقل كمية الإحتراق و يؤدي هذا إلى زيادة في الإنبعاثات الضارة. يكون عُطل المستشعر بسبب عدم تغير مُنقي الهواء (فلترالهواء) او بسبب عدم تركيبه بشكل صحيح. ينصح البعض بِتغير فلتر الهواء مرة كُل سنة. طبعا مِن المُمكن قيادة السيارة مع عُطل في المُستشعر لَكِن مع الوقت سوف تُلاحظ ان السيارة قد تتوقف عن العمل بشكل مُفاجىء و مِن ثُم عليك إعادة تشغيلها.


مشكلة في شمعات الإحتراق او اسلاك شمعات الإحتراق 

 عِند تعطل إحدى شمعات الإحتراق, قد تُلاحظ وُجود إهتزاز عِند تسارع السيارة. عِند تعطل إحدى الشمعات, مِن الأفضل إستِبدالها فورا.

توجد العديد مِن الأسباب غير المذكورة بالأعلى و اللتي قد تُؤدي إلى ظهور التحذير. هذه الأسباب هي الأكثر شيوعاً.
مصدر المعلومات:

بالنسبة لسيارتي, عِند تحريك غِطاء خزان الوقود لاحظت ان التحذير يختفي و بعدها يعود مِن جديد بعد فترة. ربما قد يكون هو السبب و ربما لا. حاليا قررت شراء جهاز خاص لفحص كمبيوتر السيارة للتأكد من المشكلة بِنفسي بدلا عن الذهاب لِأحد الوُرش. هذا الجهاز يٌباع على الإنترنت و سعره حوالي 50 ريال. سوفَ اقوم بالكتابة عن تجربتي مع الجهاز إذا قمت بشرائه و إستخدامه مع سيارتي.