Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / First Aid / March 2004

Tip: Looking for answers? Try searching our database.

Java "switch" ?

Thread view: 
Randy Tingley - 12 Mar 2004 23:59 GMT
I am having a bit of problem with my Java switch statement,
using "case".
Could someone suggest what I might be missing.
Thank you!

code below ******
import TerminalIO.KeyboardReader;
import java.text.NumberFormat;
import BreezySwing.Format;

public class GradingScaleCase {
  public static void main(String [] args) {
     KeyboardReader reader = new KeyboardReader();
     int Grade;
     String str, gradestr;

 //Input Grade
 Grade = reader.readInt("Enter Grade (Integer 1 - 100): ");

 switch (Grade){

 case (Grade >=96 && Grade <=100)
  str = "A+";
  gradestr = "Your Letter Grade is:  " + (str);
        System.out.print (gradestr); break;

 case (Grade >=92 && Grade <=95)
  str = "A";
  gradestr = "Your Letter Grade is:  " + (str);
        System.out.print (gradestr);break;

 case (Grade >=90 && Grade <=91)
  str = "A-";
  gradestr = "Your Letter Grade is:  " + (str);
        System.out.print (gradestr); break;

 case (Grade >=86 && Grade <=89)
  str = "B+";
  gradestr = "Your Letter Grade is:  " + (str);
        System.out.print (gradestr); break;

 case (Grade >=82 && Grade <=85)
  str = "B";
  gradestr = "Your Letter Grade is:  " + (str);
        System.out.print (gradestr); break;

 case (Grade >=80 && Grade <=81)
  str = "B-";
  gradestr = "Your Letter Grade is:  " + (str);
        System.out.print (gradestr); break;

 case (Grade >=76 && Grade <=79)
  str = "C+";
  gradestr = "Your Letter Grade is:  " + (str);
        System.out.print (gradestr); break;

 case (Grade >=72 && Grade <=75)
  str = "C";
  gradestr = "Your Letter Grade is:  " + (str);
        System.out.print (gradestr); break;

 case (Grade >=70 && Grade <=71)
  str = "C-";
  gradestr = "Your Letter Grade is:  " + (str);
        System.out.print (gradestr); break;

 case (Grade >=66 && Grade <=69)
  str = "D+";
  gradestr = "Your Letter Grade is:  " + (str);
        System.out.print (gradestr); break;

 case (Grade >=62 && Grade <=65)
  str = "D";
  gradestr = "Your Letter Grade is:  " + (str);
        System.out.print (gradestr); break;

 case (Grade >=60 && Grade <=61)
  str = "D-";
  gradestr = "Your Letter Grade is:  " + (str);
        System.out.print (gradestr); break;

 case (Grade >=0 && Grade <=59)
  str = "F";
  gradestr = "Your Letter Grade is:  " + (str);
        System.out.print (gradestr); break;
 }

 //else
  //System.out.println("Houstin We Have a Problem ...");

  }
}
Bjorn Abelli - 13 Mar 2004 00:30 GMT
"Randy Tingley" wrote...

> I am having a bit of problem with my Java switch statement,
> using "case".
> Could someone suggest what I might be missing.

The syntax for switch statements is as follows:

switch (expressionToTest)
{
   case expression1 : [sentences]

  [case expression2 : [sentences]]

  [default : [sentences]]
}

The expressions are not allowed to take on boolean values, just single
integral numeric values.

In your case, you'll be better of to reconstruct it with ordinary
if-elses...

// Bjorn A
Randy Tingley - 13 Mar 2004 00:36 GMT
Thank you!
To us the case, I will have to convert to an intenger.

> "Randy Tingley" wrote...
>
[quoted text clipped - 20 lines]
>
> // Bjorn A
Bjorn Abelli - 13 Mar 2004 00:42 GMT
"Randy Tingley" ...
> Thank you!
> To us the case, I will have to convert to an intenger.

Well, since you need *intervals* in your example, that wouldn't help in this
case, unless you want to line up 100 cases...

The expressions in each case must be *single* integral values...

You're still better off with if-elses... :-)

// Bjorn A

> "Bjorn Abelli" wrote...
> > "Randy Tingley" wrote...
[quoted text clipped - 21 lines]
> >
> > // Bjorn A
Dale King - 20 Mar 2004 16:10 GMT
> "Randy Tingley" ...
> > Thank you!
> > To us the case, I will have to convert to an intenger.
>
> Well, since you need *intervals* in your example, that wouldn't help in this
> case, unless you want to line up 100 cases...

And if you'd like to see that change in the future feel free to vote for bug
4269827 which is the RFE I submitted to add ranges and lists to case
statements.

--
 Dale King
cg_news - 13 Mar 2004 00:36 GMT
> "Randy Tingley" wrote...
>
[quoted text clipped - 20 lines]
>
> // Bjorn A

I agree.
Additionally, you are missing the colon ':' required after your case
statements. Correct this and you should see an error similar to:

GradingScaleCase.java:(LINE#): incompatible types
found   : boolean
required: int

As Bjorn mentioned above, though, I would recommend using if statements...

Carl.
Randy Tingley - 13 Mar 2004 00:53 GMT
Yes, you are correct!
I will try the code with if, else if's.
Thank you!

> > "Randy Tingley" wrote...
> >
[quoted text clipped - 32 lines]
>
> Carl.
Randy Tingley - 13 Mar 2004 01:03 GMT
Using the if/esle if is the most efficient manner.
I was trying to find a better way.
Thank you all very much.

import TerminalIO.KeyboardReader;
import java.text.NumberFormat;
import BreezySwing.Format;

public class GradingScale {
  public static void main(String [] args) {
     KeyboardReader reader = new KeyboardReader();
     int Grade;
     String str, gradestr;

 //Input Grade
 Grade = reader.readInt("Enter Grade (Integer 1 - 100): ");

 //If for Letter Grade A+
 if (Grade >=96 && Grade <=100){
  str = "A+";
  gradestr = "Your Letter Grade is:  " + (str);
        System.out.print (gradestr);
  }

 //If Grade is A
 else if (Grade >=92 && Grade <=95){
  str = "A";
  gradestr = "Your Letter Grade is:  " + (str);
        System.out.print (gradestr);}

 //If Grade is A-
 else if (Grade >=90 && Grade <=91){
  str = "A-";
  gradestr = "Your Letter Grade is:  " + (str);
        System.out.print (gradestr);}

 //If Grade is B+
 else if (Grade >=86 && Grade <=89){
  str = "B+";
  gradestr = "Your Letter Grade is:  " + (str);
        System.out.print (gradestr);}

 //If Grade is B
 else if (Grade >=82 && Grade <=85){
  str = "B";
  gradestr = "Your Letter Grade is:  " + (str);
        System.out.print (gradestr);}

 //If Grade is B-
 else if (Grade >=80 && Grade <=81){
  str = "B-";
  gradestr = "Your Letter Grade is:  " + (str);
        System.out.print (gradestr);}

 //If Grade is C+
 else if (Grade >=76 && Grade <=79){
  str = "C+";
  gradestr = "Your Letter Grade is:  " + (str);
        System.out.print (gradestr);}

 //If Grade is C
 else if (Grade >=72 && Grade <=75){
  str = "C";
  gradestr = "Your Letter Grade is:  " + (str);
        System.out.print (gradestr);}

 //If Grade is C-
 else if (Grade >=70 && Grade <=71){
  str = "C-";
  gradestr = "Your Letter Grade is:  " + (str);
        System.out.print (gradestr);}

 //If Grade is D+
 else if (Grade >=66 && Grade <=69){
  str = "D+";
  gradestr = "Your Letter Grade is:  " + (str);
        System.out.print (gradestr);}

 //If Grade is D
 else if (Grade >=62 && Grade <=65){
  str = "D";
  gradestr = "Your Letter Grade is:  " + (str);
        System.out.print (gradestr);}

 //If Grade is D-
 else if (Grade >=60 && Grade <=61){
  str = "D-";
  gradestr = "Your Letter Grade is:  " + (str);
        System.out.print (gradestr);}

 //If Grade is F
 else if (Grade >=0 && Grade <=59){
  str = "F";
  gradestr = "Your Letter Grade is:  " + (str);
        System.out.print (gradestr);}

 else
  System.out.println("Houstin We Have a Problem ...");

 // reader.pause();
  }
}
Ryan Stewart - 13 Mar 2004 04:32 GMT
> Using the if/esle if is the most efficient manner.
> I was trying to find a better way.
[quoted text clipped - 31 lines]
>    gradestr = "Your Letter Grade is:  " + (str);
>          System.out.print (gradestr);}
*snip*

One more minor point... It's not necessary to check the upper and lower
bounds each time.
if (Grade > 100) {
   ...
} else if (Grade >= 96) {
   ...
} else if (Grade >= 92) {
   ...
} else if ......

This code is equivalent to the code you have and a little easier to follow.
Randy Tingley - 13 Mar 2004 12:00 GMT
Thank you for showing me new ways that my
books do not show.

> > Using the if/esle if is the most efficient manner.
> > I was trying to find a better way.
[quoted text clipped - 44 lines]
>
> This code is equivalent to the code you have and a little easier to follow.
Andrew Hobbs - 13 Mar 2004 06:55 GMT
> Using the if/esle if is the most efficient manner.
> I was trying to find a better way.
> Thank you all very much.

You could do a lot to tidy it up.  For example, use  if / else but only to
set the grade,
and check at the beginning to see if within appropriate bounds etc

import TerminalIO.KeyboardReader;
import java.text.NumberFormat;
import BreezySwing.Format;

public class GradingScale {
   // A good idea to keep the actual strings / grades at the top like this.
If these change only have one place to change.  Plus available to
   // other classes.
   public static final String[] grades = { "A+", "A", "A-", "B+", "B",
"B-", "C+", "C", "C-", "D+", "D", "D-", "F",  };
   public static final int[] cutoffs =       { 96,    92,   90,    86,
82,  80,    76,    72,   70,   66,    62,   60,   };

  // normally this would all be in a method of course rather than main.
   public static void main(String [] args) {
     KeyboardReader reader = new KeyboardReader();
     String gradestr = "";

     //Input Grade
     int grade = reader.readInt("Enter Grade (Integer 1 - 100): ");

   // Good idea to test at the beginning for validity.
   if(grade <= 100 && grade >= 0) {
         //If for Letter Grade A+
         if (grade >=cutoffs[0]) {
              str = grades[0];

         // You don't need to check both bounds since it can't possibly be
above 95 or would have been caught previously
         //If grade is A
         else if (grade >= cutoffs[1]) {
              str = grades[1];

         //If Grade is A-
         else if (grade >= cutoffs[2]) {
              str = grades[2];

         //If Grade is B+
         else if (grade >= cutoffs[3]) {
              str = grades[3];

         //If Grade is B
         else if (grade >= cutoffs[4]) {
              str = grades[4];

         //If Grade is B-
         else if (grade >= cutoffs[5]) {
              str = grades[5];

         //If Grade is C+
         else if (grade >= cutoffs[6]) {
              str = grades[6];

         //If Grade is C
         else if (grade >= cutoffs[7]) {
              str = grades[7];

         //If Grade is C-
         else if (grade >= cutoffs[8]) {
              str = grades[8];

         //If Grade is D+
         else if (grade >= cutoffs[9]) {
              str = grades[9];

         //If Grade is D
         else if (grade >= cutoffs[10]) {
              str = grades[10];

         //If Grade is D-
         else if (grade >= cutoffs[11]) {
              str = grades[11];

         // Any other result getting to here must be < 60 && >= 0.
         //If Grade is F
          else {
              str = grades[12];

      gradestr = "Your Letter Grade is:  " + (str);
   }
   else {
      gradestr  = "Houstin We Have a Problem ...";
   }

   // You only need one print statement.
   System.out.print (gradestr);}

 // reader.pause();
  }
}

// Well it is a warm lazy Saturday afternoon and you did provide a code
sample.

Cheers

Andrew

--
********************************************************
Andrew Hobbs   PhD

MetaSense Pty Ltd     -    www.metasense.com.au
Australia

61 8 9246 2026
metasens AntiSpam @iinet dot net dot au

*********************************************************
Randy Tingley - 13 Mar 2004 11:59 GMT
This is very interesting!
Thank you!

> > Using the if/esle if is the most efficient manner.
> > I was trying to find a better way.
[quoted text clipped - 113 lines]
>
> *********************************************************
Antti Salonen - 13 Mar 2004 13:42 GMT
> You could do a lot to tidy it up.  For example, use  if / else but only to
> set the grade,
>  and check at the beginning to see if within appropriate bounds etc

Grades and cutoffs in tables are good, but also that can be tidied up.
IMO there's too much innecessary duplicate code in if-elses. How about
something like this:

public class Grade {

   public static final String[] grades = { "A+", "A", "A-", "B+", "B",
       "B-", "C+", "C", "C-", "D+", "D", "D-", "F",  };
   public static final int[] cutoffs =       { 96,    92,   90,    86,
       82,  80,    76,    72,   70,   66,    62,   60,   };

   /** static method to get grade-string corresponding to given points.
    * @throws IllegalArgumentException if points outside 0-100 */
   public static String getGradeString(int points) {
       // check that points is legal
       if (points < 0 || points > 100) throw new IllegalArgumentException("Illegal points, must be
within 0 and 100");
       // get grade-string by iterating through cutoffs
       String gradeString = grades[grades.length-1]; // init to "F"
       for (int i=0; i<cutoffs.length; i++) {
           if (points >= cutoffs[i]) {
               gradeString = grades[i];
               break; // found correct grade, abort loop
           }
       }
       return gradeString;
   }

   // testing..
   public static void main(String[] args) {
       //System.out.println(Grade.getGrade(101).getGrade()); throws exception
       System.out.println(Grade.getGradeString(100));
       System.out.println(Grade.getGradeString(96));
       System.out.println(Grade.getGradeString(72));
       System.out.println(Grade.getGradeString(60));
       System.out.println(Grade.getGradeString(59));
       //System.out.println(Grade.getGrade(-1).getGrade()); throws exception
   }

}

Grades could also be thought as objects, then the class could look
something like this:

public class Grade {

   public static final String[] grades = { "A+", "A", "A-", "B+", "B",
       "B-", "C+", "C", "C-", "D+", "D", "D-", "F",  };
   public static final int[] cutoffs =       { 96,    92,   90,    86,
       82,  80,    76,    72,   70,   66,    62,   60,   };

   // private fields
   private String grade;
   private int points;

   /** constructor is not accessible outside Grade-class, you must use
    * static getGrade-method to get Grade-object */
   private Grade(String grade, int points) {
       this.grade = grade;
       this.points = points;
   }

   /** static method to get Grade-object corresponding to given points.
    * throws exception if points outside 0-100 */
   public static Grade getGrade(int points) {
       String gradeString = getGradeString(points);
       // create new Grade-object with grade-string and points-integer
       Grade grade = new Grade(gradeString, points);
       // return grade-object
       return grade;
   }

   /** static method to get grade-string corresponding to given points.
    * throws exception if points outside 0-100 */
   private static String getGradeString(int points) {
       // check that points is legal
       if (points < 0 || points > 100) throw new IllegalArgumentException("Illegal points, must be
within 0 and 100");
       // get right grade-string by iterating through cutoffs
       String gradeString = grades[grades.length-1]; // init to "F"
       for (int i=0; i<cutoffs.length; i++) {
           if (points >= cutoffs[i]) {
               gradeString = grades[i];
               break;
           }
       }
       return gradeString;
   }

   /** accessor for grade-field */
   public String getGrade() {
       return grade;
   }

   /** accessor for points-field */
   public int getPoints() {
       return points;
   }

   /** Returns a string representation of the object. */
   public String toString() {
       return grade;
   }

   // testing..
   public static void main(String[] args) {
       //System.out.println(Grade.getGrade(101).getGrade()); throws exception
       System.out.println(Grade.getGrade(100));
       System.out.println(Grade.getGrade(96));
       System.out.println(Grade.getGrade(72));
       System.out.println(Grade.getGrade(60));
       System.out.println(Grade.getGrade(59));
       //System.out.println(Grade.getGrade(-1).getGrade()); throws exception
   }

}
Andrew Hobbs - 13 Mar 2004 14:16 GMT
> > You could do a lot to tidy it up.  For example, use  if / else but only to
> > set the grade,
[quoted text clipped - 40 lines]
>
> }

Yes definitely better in this case.

Cheers

Andrew

> Grades could also be thought as objects, then the class could look
> something like this:
[quoted text clipped - 71 lines]
>
> }
Randy Tingley - 13 Mar 2004 14:22 GMT
Thank you!
I am really learning more than my books have!
This is another EXCELLENT example!
I knew that there had to be better ways. :)

> > You could do a lot to tidy it up.  For example, use  if / else but only to
> > set the grade,
[quoted text clipped - 116 lines]
>
> }
Andrew Thompson - 13 Mar 2004 15:05 GMT
> Thank you!
> I am really learning more than my books have!
> This is another EXCELLENT example!

Another excellent example of _trimming_
for both you and Andrew H.
<http://www.physci.org/codes/javafaq.jsp#netiquette>
..with particular note that you both
beat the 140 lines listed as an example.

Signature

Andrew Thompson
* http://www.PhySci.org/ Open-source software suite
* http://www.PhySci.org/codes/ Web & IT Help
* http://www.1point1C.org/ Science & Technology

Roedy Green - 17 Mar 2004 01:55 GMT
>  case (Grade >=76 && Grade <=79)
>   str = "C+";
>   gradestr = "Your Letter Grade is:  " + (str);
>         System.out.print (gradestr); break;

cases don't take booleans.    You have to spell it out longhand
case 76:
case 77:
...

Note that you repeat the code:

gradestr = "Your Letter Grade is:  " + (str);      
System.out.print (gradestr);

In every case.  Factor it out after the end of the switch.

--
Canadian Mind Products, Roedy Green.
Coaching, problem solving, economical contract programming.
See http://mindprod.com/jgloss/jgloss.html for The Java Glossary.


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.