This week's book giveaway is in the Agile and Other Processes forum.
We're giving away four copies of Darcy DeClute's Scrum Master Certification Guide: The Definitive Resource for Passing the CSM and PSM Exams and have Darcy DeClute on-line!
See this thread for details.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Jeanne Boyarsky
  • Tim Cooke
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Tim Moores
  • Mikalai Zaikin
  • Carey Brown
Bartenders:

If/Else/Switch Statements

 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have pulled up quite a few websites trying to explain.. if, else, switch statements.
I am having a difficult time placing it in code.
I have a project - Below are the instructions to the program and what I've formulated so far.
Do I have to define A,B,C,D before putting it in the switch statement? What am I missing?







Project Objectives:
• To develop skills in using the Java selection constructs (if, if else, and switch),
• To further explore some of the String class's capabilities
• To look at displaying the attributes of an object
• To become familiar with basic UML class diagrams
Prep Readings:
Big Java textbook, Chapters 1 - 5.
Background Information:
The Unified Modeling Language (UML) provides a useful notation for designing and developing object-oriented software systems. One of the basic components of the UML is a class diagram, which are used to depict the attributes and behaviors of a class. A basic class diagram (as shown in the figure below) has three components. The first is the class name. The second component includes the class's attributes or fields. Each attribute is followed by a colon ( and its data type. The third component includes the class's behaviors or methods. If the method takes parameters, their types are included in parentheses. Each behavior is also followed by a colon ( and its return type. If the return value of a method is void, the return type can be omitted. For more information on the UML, refer to http://www.uml.org/.

Project Requirements:

1. We are going to develop a simple class that represents a pay-per-view movie customer and determines the cost of watching a movie using Fox Cable Company's pay-per-view movie service, based on the movie's ratings and whether it is a new release or a rare movie. For example, the movie "The Departed" has a rating of A, and since it is a new release, the movie will cost extra. The movie "Howard the Duck" has a rating of F, and since it is a rare movie, it will cost extra as well. The Viewer class represents an individual customer who purchased a pay-per-view movie.
2. Design and build a Viewer class. The class will have three instance fields (or instance variables as they are also called). There will be a customer variable that will hold the customer's name. The class will also have a movieCode variable that will store the quality of movie based on its rating and whether it is new or rare. Finally, a cost variable that will store the total cost for the movie. This class should have a parameterized constructor, accessor methods for the instance fields, a method to compute the cost of the movie, a method to update the movie's rating, and a method to convert the state of the object to a String. Using the UML, the class diagram for the Viewer class looks like this:

Viewer

Customer : String
movieCode : String
cost : double

Viewer(String, String)
getCustomer() : String
getMovieCode() : String
getCost() : double
computeCost()
updateMovieCode(String)
toString(): String


• The constructor will assign the first parameter to the variable customer and the second to the movieCode variable. The constructor will then call computeCost() to convert the movie code to the numeric cost and store it in cost variable.
• The class will have three accessor methods getCustomer(), getMovieCode(), and getCost(). Each will return the value of the respective instance variable.
• The method computeCost() handles the conversion of the movie code to cost and saves it in the instance variable cost. Movie codes consist of a rating letter (A, B C, D, or F) and an optional character (N or R) to identify if the movie is a new release or rare. The base price of a movie is $3.95. The price of the movie increases as the quality of movie increases according to the table below:

Movie Rating Price Factor
A 1.50
B 1.36
C 1.26
D 1.06
F 1.00





• The optional movie modifier can have one of two possible values to indicate whether the movie is new (N) or the movie is rare (R). A rare movie adds $1.00 to the base price, while a new movie adds $2.50 to the base price. Note that F list movies always have a rare (R) modifier. For example, a movie code value of "A"(no modifier) would cost 3.95 * 1.50 = $5.93, a movie code value of "AN" would cost (3.95 + 2.50) * 1.50 = $9.65, and a movie code value of "BR" would cost (3.95 + 1.00) * 1.36 = $6.73

You must use the switch statement to determine the proper price factor using the ratings, and use the if else construct to handle the movie modifiers.

• The class will have a method updateMovieCode (String) that takes a new movie code and updates the movieCode and cost variables accordingly. Use the computeCost() method to update the cost. Note that we can call methods of a class from within the class; in this case, we do not use the dot (.) operator. Methods which are useful to other methods are called utility methods, and do not need to be public if they will only be called from within the class. The computeCost() method is a utility method, and should be defined as a private method.
• The method toString() allows us to access the state of the object in a printable or readable form. It converts the variables to a single string that is neatly formatted. Look at pages 161 -162 of the text for a discussion of escape sequences. These are characters that you can insert into your strings and, when printed, will format the display neatly. You can insert an escape sequence for the tab character and get a tabular form when printing. This tab character is '\t'. Your class will have a toString() method that concatenates customer, movieCode and cost separated by tab characters and returns this new string. When you try to print an object, thetoString() method will be implicitly called. For example, if John Snow watched a movie that had a movie code value of "DR", the output would be:
John Snow DR $5.24


3. Build a class ViewerTest that will test the constructor and all the public methods of the Viewer class. Generate objects that have each of the possible values for a movie code and print each object by implicitly calling the toString() method on each object. Note that there will be 13 valid movie codes since the movie modifier is optional and an F rating always has the rare (R) modifier (A, AN, AR, B, BN, BR, C, CN, CR, D, DN, DR, and FR). Remember to test for invalid movie codes as well (for example, G, BA, H3, etc). Invalid movie codes should display an error message and set the cost to $9999.99. Your program should ignore case in movie code values. For example, a movie code value of "an" should be processed the same as "AN".

Implementation Notes:
You should use both the switch and the if else constructions in this program. The switch construction is good when you are checking a single variable against a number of different discrete values. A character variable (char) is discrete (you have one of a set of characters only) as are integral types (int). Strings and floating-point numbers are not discrete and will not work with the switch statement. if statements can be used anytime you have a relational operation such as equality, less than, etc. But you need to be careful when using a long series of if {...} else {...} constructs because of the confusion factor (Which if does this else go with? Where am I in this sequence of tests?).
• Strings have many behaviors or methods available. These behaviors include finding an individual character in the string, telling how many characters are in the string and converting the contents of the string to either upper or lower case. You will need to use the charAt(int i) method to extract the movie rating and movie modifier from the movieCode string to work with. For example, suppose you have a Java statement:
String x = "This is a string.";
You can extract the period at the end of the statement by using the Java statement:
char period = x.charAt(16);
This will extract the 17th character in the string and place it in the variable period. Remember that string numbering starts at 0, not 1. A better way to do this would be to use the length()method of the String class, which tells us how many characters are in the string. So we can use it to tell us where the period is since we know it is the last character (in this specific case) in the string. So the Java statement:
int howLong = x.length();
tells us the number of characters. But the numbering starts at zero, so if we want to access the last character, we have to reduce howLong by 1. Then we could do:
char period = x.charAt(howLong - 1);
to get the same result as in the second statement above.
Experienced programmers would probably simplify the construction slightly more by eliminating the variable howLong if this is the only use of it. We could then re-write it as:
char period = x.charAt(x.length() - 1);
Note how we are nesting method calls inside of other method calls. This can be a very powerful programming technique.
You should also use the toUpperCase()method of the String class to convert the movie code to upper case characters before processing it. For example, you should convert the movie code "an" to "AN." If you do this when the value is first stored in the object, you only have to process upper case characters in your computeCost()method.







 
Bartender
Posts: 563
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You need to learn to use the online API and tutorials. Here's the tutorial for the switch statement, found using a simple Google search like "java switch":

http://download.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

Then, try to focus your questions a bit, reducing the content of your post to what really matters. Fix up your switch statement, consider reviewing the If/Else tutorial, then come back if you need help.
 
Heather Dennison
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yea.. I've already read the API on switchs and if statements. . . I think I am making this harder than it is. I'm getting everything confused. In the examples, they have the systemoutprint within each case. I thought this would go in the tester class..
 
Ranch Hand
Posts: 82
2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The program as written will not compile. Your switch statement has switch(C). You need to have one of the following primitive data types: byte, short, char, and int. That means you will need to have something like switch('C'). Also the case() must have one of those primitive data types. Using the System.out.println will help you to see what is happening in the within the computeCost() method so you can determine if the program is working as expected.

You will also need to correct you if statement. It must evaluate true or false. So you could have if(movieCode.length()>1)
 
Heather Dennison
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Larry--- this has helped so much.. I am now working the if statement. I would like to run to see what it generates.


The error that I get is with the ---if(movieCode[1] = ('N')) and ----else if(movieCode[1]=('R'))

error message -----Viewer.java:50: array required, but java.lang.String found
if(movieCode[1] = ('N'))

I am trying to compute ... if there is a "N" in the first space of the word then multiply the cost by a certain amount. If neither "N" or "R" then the cost is set to 9999.99


 
Marshal
Posts: 28009
94
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You have confused "=" (which assigns the value on the RHS to the variable on the LHS) with "==" (which compares the value on the RHS to the value on the LHS).
 
Heather Dennison
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator



I changed the "=" to "==" and it still errors.

ERROR----Viewer.java:56: array required, but java.lang.String found
if(movieCode [1] == ('N'))

It's like ...it does not like the [1]
 
lowercase baba
Posts: 13089
67
Chrome Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
you have declared your movieCode variable as a String - a String in Java is NOT an array (like it is in C), and cannot be treated as such. You'd need to use something like the charAt() method.
 
Marshal
Posts: 78695
374
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You have several errors going on simultaneously. Divide and rule. Get rid of a lot of that code, by commenting it out, like this:Then errors in that code can't affect the rest of it.

Get one bit working, then take the // out and try the remainder. It's much easier to deal with small bits of code with a few errors than large swathes of code with many errors.

Also get yourself a decent text editor which supports bracket matching, syntax colouring and automatic indentation. Not NotePad, but NotePad2, jEdit, NotePad++ (all of which I have used, and other recommend TextPad) . It will take care of indentation, which is inconsistent in this code. Don't use tabs for indenting. Use spaces (probably 4 at a time).
 
Heather Dennison
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Excellent help, guys! Finally finished the product. I think I will run it through a text editor. I have never had a programming class before. So needless to say... this site has been extremely helpful. Thanks again!
 
Campbell Ritchie
Marshal
Posts: 78695
374
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You're welcome
 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Is there a tester for this?

and if there is what would that be?
 
Bartender
Posts: 10780
71
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Heather Dennison wrote:Excellent help, guys! Finally finished the product. I think I will run it through a text editor. I have never had a programming class before. So needless to say... this site has been extremely helpful. Thanks again!


You're welcome. It may be worth pointing out that you could have used a switch statement for the previous 'if', viz:Personally, I find them a lot easier to read (and to update, if needed); but they do have a MAJOR drawback:
That &#@$! break statement is required; and even after all these years, I sometimes forget it.

Winston
 
Campbell Ritchie
Marshal
Posts: 78695
374
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ryan Nelson, welcome to the Ranch

I am afraid I don’t quite understand your question. What would a tester program do?
 
fred rosenberger
lowercase baba
Posts: 13089
67
Chrome Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
also note that this thread is well over a year old, so I would guess the OP has moved on to other things by now...
 
Winston Gutkowski
Bartender
Posts: 10780
71
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

fred rosenberger wrote:also note that this thread is well over a year old, so I would guess the OP has moved on to other things by now...


Aaargh. Doh-h-h!

Winston
 
Ryan Nelon
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
a tester program to see if the program work....

for example "john" saw 'A' movie
the result should show cost

mary saw 'B' movie
the result should show cost

it shows for each type of movie.

what would the ViewerTester look like?

something like:



Viewer v1 = new Viewer("John", "A");

get cost..


Viewer v2 = new Viewer("Mary", "B");
get cost...
System.out.println(v2.toString());
 
Campbell Ritchie
Marshal
Posts: 78695
374
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think you have answered the question. Obviously you can have such a tester. In fact when you are learning to write these things you should have a runApplication() or similar method which goes through all your methods anmd supplies lots of different options so you can see them working.
Another way to do it is to pass parametersIt should be obvious from the above that Foo has a constructor taking an int parameter, and foo() bar() baz() biz() boz() and buz(int) methods. I have assumed that the buz(int) method might throw an IllegalArgumentException (IAE) for negative arguments. Since IAE is unchecked, you would not normally catch it, but this program is a “what happens if” program where it is appropriate to make sure it runs to completion regardless. You also need a correctly-overridden toString() method in Foo to give you any sort of understandable output.

To get the command-line arguments, you would invoke the program like this, and you can see from the output how the different arguments are handled:Obvioiusly you can alter that sort of thing to test if-elses and switch-cases, exactly as you wrote yourself.
 
Is this the real life? Is this just fantasy? Is this a tiny ad?
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic