java - Fully utilizing a switch statement -


my java textbook asked me following error:

switch (score)         {             case (score > 90):                 grade = 'a';                 break;             case (score > 80):                 grade = 'b';                 break;             default:                 grade = 'c';         } 

i know error is:

  • switch statements aren't built comparisons (score > 90); that's if/else statements.

but got me wondering: how could switch statement efficiently account ranges of integers?

the obvious example think of below, find rather brute-force:

switch (score)     {         case 90: case 91: case 92: case 94: case 95:         case 96: case 97: case 98: case 99: case 100:             grade = 'a';             break;         case 80: case 81: case 82: case 84: case 85:         case 86: case 87: case 88: case 89:             grade = 'b';             break;         default:             grade = 'c';     } 

how else concept expressed in switch statement?

if take advantage of fact grades change every change of 10 in score, , assuming score integer data type, can divide 10 eliminate cases:

switch (score / 10) {     case 9:     case 10:         grade = 'a';         break;     case 8:         grade = 'b';         break;     default:         grade = 'c'; } 

if there no such rule (if "grade" bucket sizes differing , arbitrary), best can if/else-if/else statements.


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -