wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Is This Switch Correct and Efficient? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Is This Switch Correct and Efficient?" Watch "Is This Switch Correct and Efficient?" New topic
Author

Is This Switch Correct and Efficient?

Robin Lane
Ranch Hand

Joined: Apr 30, 2008
Posts: 76
Disclaimer: The author of this post makes no claims, implied or otherwise, as to her ability to understand anything but the simpliest of answers. Further, the author of this post has no programming background whatsoever and is in Week 6 of Java Programming class. She does want to learn, so please teach patiently.

Here's my situation. I am writing an inventory program as a class assignment. We get to choose the type of product, so I have chosen movies. (I'm a huge movie fan!) I am not required but want to put a user-entered variable to track genre or category. My relatively uneducated thought was that a switch selection statement would work best, because a) it keeps genres or categories consistent (not one person entering Horror and another entering Zombie or Hack and Slash) and b) a report listing the number of titles in each genre can be obtained. It's a functionality thing from my perspective.

Here's my kindergartner Java code for my switch:

//Switch Statement for Genre Selection, Movies class, Inventory Program

Variables:



My variables would be declared with my class variables and arrays. I just separated the counters out here to give a more complete picture of my genres and switch choices.

Is this a good switch statement? Or does it need to be re-designed? Or does it need to be scratched, altogether?


Disclaimer: The author of this post makes no claims, implied or otherwise, as to her ability to understand anything but the simplest of answers. Further, the author of this post has no programming background whatsoever and has taken one Java Programming class which was 9 weeks long. She does want to learn, so please teach patiently.
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11152
    
  16

I don't understand this:
switch (category/14 )

why are you dividing by 14? Generally you want to avoid these 'magic numbers'. anyone (like me) looking at this code is going to say "Why 14? why not 17, or 23?".

otherwise, i don't see anything obviously wrong. It may not actually be the best implementation, but it should work.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Daesung Park
Ranch Hand

Joined: Mar 22, 2007
Posts: 68
1. "category%14" instead of "category/14"?

2. How about considering as below

Switch is not efficient in dealing with lots of cases.


Daesung Park

BLOG
Robin Lane
Ranch Hand

Joined: Apr 30, 2008
Posts: 76
I don't understand this:
switch (category/14 )


Fred, I honestly didn't understand it. It was in the example given in my textbook but no explanation was provided. Therefore, I "assumed" it was necessary. Apparently, it is not and that's good news! Because now I understand more than I did. I... think. (shrugs it off) Anyway, can I just get rid of that bit then? Without any weird affect on my overall switch statement?
Larry Frissell
Ranch Hand

Joined: May 16, 2008
Posts: 82
    
    2
As Daesung Park pointed out the code should most likely be "category%14" instead of "category/14". The % is used to prevent an error due to a user entering in a number other than 1 through 14. For example if you enter a 16 the result is the same as entering 2.
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11152
    
  16

Larry,
The switch has a default that would catch anything greater than 13 and lump them together. I was trying to keep things simple, as Robin states she is a beginner...

Robin, here's what we're talking about. when you say (num/14), it is doing an integer division. that's like from grade school, where you say 34 divided by 5 is 6, remainder 4, except you throw away the remainder. So, with what you have, if the user enters ANYTING from 0-13, your division will result in 0. anything entered from 14 to 27 will return 1, and so on.

the '%' character is the other half of that grade school division. You keep the remainder, but throw away the quotient. so, 17 % 14 would return 3 (because 17 divided by 14 is 1, remainder 3).

Honestly, what you should probably do is something like this:



This way, if the user inputs something you don't want to allow, you tell them why it's not valid (note - you could make a categor 14 of "other" if you wanted, with appropriate modifications...)

On the other hand, you may WANT to count anything other than 1-13 as one big lump... these are the kinds of decisions developers have to make all the time.
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11152
    
  16

one other thing... You ask about 'efficient'. Optimization is a whole other ball of wax. General advice is 'write the code that is easiest to understand first'. once it's done, see if it is fast enough. if not, THEN go back and re-engineer the slow bits. FINDING where you code really is slow is the trick. lots of time is wasted on 'pre-mature optimization'. the bottlenecks in any code is usually NOT where you think it is, so it's generally not worth time guessing.

We have an entire forum devoted to optimization, but i think that is getting ahead of where you seem to be. I wouldn't worry about that part now.

:-)
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Daesung Park:

Switch is not efficient in dealing with lots of cases.


Is it not? Where do you get that from? And how many is "lots"?


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Robin Lane
Ranch Hand

Joined: Apr 30, 2008
Posts: 76
(mulling over all the wonderful responses) Okay... let me make sure I am properly processing what I've been taught.

First, my switch parameter should probably have been category % 14, using the remainder operator (%) instead of the division operator (/). Got it, and it makes sense! (This is always good! ) Therefore, if category needed a validation that could be handled by an expression that resulted in 0 or 1 (basically, true or false), then the division or remainder operators would be appropriate. However, since I had a default case in my switch, I had a "fall through" prevention in place to catch any numbers other than 1 - 13. I would just need to add a miscellaneous counter to keep track of any category numbers that aren't 1 - 13. Is this correct?

Second, Park suggested the use of an array, if I read and understood his code correctly. Fred suggested a sentinel-controlled while loop which would use an if...else to validate the user entered input. Couldn't I combine them? Use an array to store the genre values and the while loop with the if...else to validate the data entered? If yes, would I write the code like this?



Third, if I created a miscellaneous category that accepted all input < 1 || > 13, the error message and re-prompt wouldn't be necessary, but perhaps I should include a message that would display the data entry and ask the user to make sure this is what they meant to enter?

Larry, thanks for the explanation (and, therefore, reminder) about using the remainder operator. (grabs her head dramatically but jokingly) This is so much to remember! I still forget little things... and big things, too, to be honest.

Fourth, could some examples be given of good switch implementation? This would be very helpful furthering my understanding of switches!

Again, thank all of you for the responses, suggestions, explanations, and help!
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11152
    
  16

I think you are very close with your code, but not quite... The idea is you would create an array of ints to be your counters for each type. the index of the array matches your 13 genre types. remember you're array will have to be 14 in size, since arrays are 0-based. it's much easier to have an array that's 1 too big and not use it (or use it for your default 'not one of my pre-defined genre counter) rather than make it 13 in size and have to do the "well, Drama is 5, so that goes into index 4" logic.
this is not right. You don't want to store the genre number in the array, but want to use the genre number as the index into your array to figure out which counter to increment.

rather, you'd get your user input, validate it (or not...), then do something like

MovieGenre[genre]++;

So, assume the user inputs '5'. this will go to the element in the array with index '5', and increment it. Then, each time you loop through and get a new input, a different element would be updated.

does that make sense?
Robin Lane
Ranch Hand

Joined: Apr 30, 2008
Posts: 76
(hamsters in the wheel that power Robin�s brain start running faster) The array creation statement would be:

Then, the array�s element indices would be used as the genre/category numbers, and 0 could be assigned as the catch-all or miscellaneous genre. The rest of the indices could be assigned as in my switch statement. To understand the purpose of the array, the movies �catalogued� in this array should be entered as additions to the appropriate counter. For example, using a pencil and paper, drawing out a series of columns, heading the columns with my genres, and placing a check mark in the Horror column for the movie Underworld. This is the real world example of an integer array for my genres. Correct? (tosses the hamsters a treat with a preoccupied look)

(lightbulb goes off) Aha! This means that I can use the element indices in my MovieTitle array as the product number. Yes?

Question: Are the array�s indices assigned automatically when the user enters input?

Also, could you give me some instances of when the use of a switch would be a good implementation? This would help further my understanding of switches and every little bit helps!
Robin Lane
Ranch Hand

Joined: Apr 30, 2008
Posts: 76
MovieGenre[genre]++;


This is an example of postincrementing, right? But... (thinks furiously) in incrementing the array does the [genre] mean that the... (pauses and sorts out the mental car crash) the input would be tells the array which index to increment? So... user input is genre 5, the code needs to take the input value of 5 and tell the array to increment the correct counter element by 1.

Is that right?
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11152
    
  16

this is post incrementing, but for the most part, if ALL you have is a variable and increment operator (either pre or post) it doesn't matter.

I would think of it this way. The array is like an egg carton, with each bin numbered. you are going to drop a pebble in the bin for each movie you have of that genre - it's a counter basically. when you say

"MovieGenre[genre]"

remember that 'genre' is really a number. you are telling the computer which bin you are talking about. it's just like saying "MovieGenre[2]" or "MovieGenre[12]". when you put that "++" on there at the end, you're basically saying:

Ok, go find the MovieGenre array. got it? good!!! now go to the bin labeled with whatever value 'genre' is holding... could be the 2nd, could be the 12th... just use whatever that variable holds to figure it out. now that you've found that, drop a pebble in the bin."


You're not telling it which INDEX to increment. the term 'index' means 'which element of the array' or 'which bucket i'm talking about'. you don't want to change that. you want to change what is IN the bucket.
Robin Lane
Ranch Hand

Joined: Apr 30, 2008
Posts: 76
You're not telling it which INDEX to increment. the term 'index' means 'which element of the array' or 'which bucket i'm talking about'. you don't want to change that. you want to change what is IN the bucket.


I'm pretty sure you and I mean the same thing. I guess it sounds weird, because I'm saying it in the way I understand it. However, I do understand that the index is really just the "label" for the element or component of the array you want to affect. So, I think we are on the same page, so to speak.

Now, let me try to clear this little bit up. Would this code be correct?

display prompt

genre = input.nextInt.();
MovieGenre[genre]++

Is that how I would write the code to take the user input for the variable genre and the increment the correct array counter element? In other words, would using the above code take a user entered value of 10 and tell the MovieGenre array to increment counter element by 1? And, if so, then whatever the user enters the corresponding counter element gets incremented? This would make the code dynamic in that it would go with the user entered number without supplying 15 individual lines of code listing each individual element? Do I have it right?
 
 
subject: Is This Switch Correct and Efficient?
 
Similar Threads
GUI Pieces and Parts Not Sticking! Help!
I WANT2 CHANGE METHOD, BUT IT DOESNT WORK, HELP~
Puzzled
Do while error, I'm going crazy
Just Java 2 clock class help required (Resolved)