[Java in NetBeans] Lesson 09. Switch / If-Else Ladder

这个课程的参考视频和图片来自youtube

    主要学到的知识点有:

1. Nested If-else statement (if-else ladder)

/**
 * 90 and above ==> A
 * 80 up to 90  ==> B
 * 70 up to 80  ==> C
 * 60 up to 70  ==> D
 * below 60     ==> F 
 */

if (grade >= 90)
{
    gradeLetter = "A";
}
else if (grade >= 80)
{
    gradeLetter = "B";
}
else if (grade >= 70)
{
    gradeLetter = "C";
}
else if (grade >= 60)
{
    gradeLetter = "D";
}
else 
{
    gradeLetter = "F";
}

2. Switch

switch (month)
{
    case 1:
        result = "January";
        break;
    case 2:
        result = "February";
        break;
    case 3:
        result = "March";
        break;
     default:
        result = "Unknown;
        break;
}

3. Enumerations

  • An enumeration custom data type  that enables a variable to be a set of predefined constants of specific value
  • Enums are declared like a class

Cannot assign to enum class.      Grade g = 78.0;    is not allowed.

Cannot create an object from  enum class.  Grade g = new Grade(88);      is not allowed.

This is a enum class of grades.

/**
 *
 * Java enum representation for grades, based on the following scale:
 * 90 and above ==> A
 * 80 up to 90  ==> B
 * 70 up to 80  ==> C
 * 60 up to 70  ==> D
 * below 60     ==> F 
 */
public enum Grade {
    
    A (90.0), B(80.0), C(70.0), D(60.0), F(0.0); // here will call the constructor
    
    private final double minimumScore;
  
    /**
     * Write a constructor for grade with minimum score for that grade
     * @param minimumScore lowest acceptable score for that grade 
     */
    Grade (double minimumScore) {
        this.minimumScore = minimumScore;
    }
    
    /**
     * Return the minimum score for the letter grade
     * @return lowest score fort achieving that grade
     */
    public double Min() {
        return this.minimumScore;
    }
            
}

If we have the enum class above, then we can rewrite the example in No.1 at beginning. 

if (grade >= Grade.A.Min())
{  
   gradeLetter = Grade.A;
}
   else if (grade >= Grade.B.Min())
{
   gradeLetter = Grade.B;
}
   else if (grade >= Grade.C.Min())
{
   gradeLetter = Grade.C;
}
   else if (grade >= Grade.D.Min())
{
   gradeLetter = Grade.D;
}
    else 
{
    gradeLetter = Grade.F;
}

猜你喜欢

转载自www.cnblogs.com/Johnsonxiong/p/10117414.html