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 / General / December 2007

Tip: Looking for answers? Try searching our database.

Help with code...

Thread view: 
DBJohnston0104@gmail.com - 29 Nov 2007 02:34 GMT
I'm trying to complete a homework assignment where a window asks for a
billType (ex: Rent, Food, Gas, etc.) and then the next window asks for
an amount.  It should keep a running total of all bills entered and
continue to loop until you enter the word "done" as a billType.  I
just don't understand why the code below doesn't work.  Now I don't
want anyone to give me the answer or the correct code, but I would
like some hints.  I'm really interested in getting this to work so
here I am.  And here is what I have so far:

// MonthlyBills.java - This program calculates the total of your
monthly bills.
// Input:  Bill type and bill amount.
// Output: Prints the total of your monthly bills.

import javax.swing.JOptionPane;

public class MonthlyBills
{
    public static void main(String args[])
    {

        String billType;     // Description of bill.
        String stringAmount;    // String version of bill amount.
        double billAmount;    // Amount of the bill.
        double sum = 0;     // Accumulates sum of bills.

        /* You should set up your loop to execute as long as the user
          has not entered the word done. You can use these input and
          output statements anywhere in your program. They are not in
          any particular order.
        */

        do
        {
            // This input statement asks the user to enter a bill type or the
word none.
            billType = JOptionPane.showInputDialog("Enter bill type or the word
done to quit.");

            if(billType != "done")
            {
                // This input statement asks your user to enter a bill amount.
                stringAmount = JOptionPane.showInputDialog("Enter amount of
bill");

                // This statement converts the string version of the amount to a
double.
                billAmount = Double.parseDouble(stringAmount);

                //This totals up the amount of the bills
                sum += billAmount;
            }

        }while(billType != "done");

            // This statement displays the sum of monthly bills.
            System.out.println("Sum of monthly bills is $: " + sum);

            // This statement causes the program to exit.
            System.exit(0);

    } // End of main() method.

} // End of MonthlyBills class.
Andrew Thompson - 29 Nov 2007 03:03 GMT
>I'm trying to complete a homework assignment ...

A good group for Java beginners is comp.lang.java.help

>...And here is what I have so far:

That code was a pretty good description of your problem,
but the lines wrapped and had to be fixed before it would
compile and the error became clear to me.

To help avoid line-wrap in code, use the TWC
<http://www.physci.org/twc.jnlp>

Here is the fixed code, with comments.  Note that this is an
SSCCE that spans only 68 characters width.  Hopefully
it should not line-wrap.

<sscce>
import javax.swing.JOptionPane;

/* MonthlyBills.java - This program calculates the total
 of your monthly bills.
Input:  Bill type and bill amount.
Output: Prints the total of your monthly bills. */
public class MonthlyBills
{
   public static void main(String args[])
   {
       /** Description of bill. */
       String billType;    
       /** String version of bill amount. */
       String stringAmount;
       /** Amount of the bill. */
       double billAmount;    
       /**  Accumulates sum of bills. */
       double sum = 0;    

       do
       {
           // This input statement asks the user to
           // enter a bill type or the word none.
           billType = JOptionPane.showInputDialog(
               "Enter bill type or the word done to quit.");

           // String comparison needs to be done using .equals()
           // to check equality of the contents, as opposed to
           // the String objects
           if(!billType.equals("done"))
           {
               // This input statement asks your user
               // to enter a bill amount.
               stringAmount = JOptionPane.showInputDialog(
                   "Enter amount of bill");

               // This statement converts the string version
               // of the amount to a double.
               billAmount = Double.parseDouble(stringAmount);

               //This totals up the amount of the bills
               sum += billAmount;
           }

       }while(!billType.equals("done"));

           // This statement displays the sum of monthly bills.
           System.out.println("Sum of monthly bills is $: " + sum);

           // This statement causes the program to exit.
           System.exit(0);

   } // End of main() method.

} // End of MonthlyBills class.
</sscce>

Signature

Andrew Thompson
http://www.physci.org/

Ravi - 29 Nov 2007 10:11 GMT
== and != does reference comparison. If you want to do object
comparison, use equals() method.
This is corrected by Andrew in his code snippet.

As an example, consider the following code
String str1 = new String("String");
String str2 = new String("String");
String str3 = str2;
System.out.println(str1==str2);
System.out.println(str2==str3);
System.out.println(str3==str1);

What does it print? Reason it out.

Regards,
Ravi.

> DBJohnston0...@gmail.com wrote:
> >I'm trying to complete a homework assignment ...
[quoted text clipped - 77 lines]
>
> Message posted via JavaKB.comhttp://www.javakb.com/Uwe/Forums.aspx/java-general/200711/1
DBJohnston0104@gmail.com - 30 Nov 2007 00:53 GMT
> DBJohnston0...@gmail.com wrote:
> >I'm trying to complete a homework assignment ...
[quoted text clipped - 77 lines]
>
> Message posted via JavaKB.comhttp://www.javakb.com/Uwe/Forums.aspx/java-general/200711/1

Andrew, you're my hero!  I have spent several nights looking at this
simple program and it was driving me nuts.  I don't think that I can
turn in your answer but I do thank you for your help.  In our book it
has example of all the operators and what they mean but not so much as
to how to use them.  The ! in front of the billType I would have never
figured out.  Thanks again!

So when you refer to a string you have to use .value() to check for
equality but not for double?  Is that right?

Thanks again,
David
Andrew Thompson - 30 Nov 2007 01:15 GMT
...
>So when you refer to a string you have to use .value() to check for
>equality

That is probably what happens, though I have never looked into
it that closely.  (shrugs) I just use .equals().

>..but not for double?  Is that right?

My understanding is 'double' no, but 'Double' yes.
The primitives are open for direct comparison, as you surmise -
all objects need to be compared using the valueOf or toString()
or a defined comparator.

OTOH, there is a "gotcha" when it comes to floating point
representations of numbers.  They should never be compared
for equality at all, since two doubles that appear on screen as
(hypothetical WAG)
1.00000000004 &
1.00000000004
..may *not* be equal.  It comes down to the reality that
digital computers do not store floating point numbers
exactly.

Signature

Andrew Thompson
http://www.physci.org/

Andrew Thompson - 30 Nov 2007 01:24 GMT
>...  I don't think that I can turn in your answer ..

Yeah, sorry.  I even had your comment that this was 'homework'
in the back of my mind as I was looking over the code.  

The thing is, I wanted to whow how short and convenient SSCCE
code can be, and besides some trivial changes to comments and
line lengths, that posted code is *very* similar to the code you
posted - only two lines are substantively different.  Since you
obviously understand the 'how and why' - you can easily adapt
that back into your original code.

BTW - It seemed odd that comparison was done twice.  It might
be a good idea to ask for 'stylistic/design advice' once the code
seems to be working.  I make a point of trying to avoid making too
many changes to any piece of code that has a specific problem.
Instead I just fix the stated problem, & post the fixed version
back to the group.

Signature

Andrew Thompson
http://www.physci.org/

DBJohnston0104@gmail.com - 30 Nov 2007 04:41 GMT
> DBJohnston0...@gmail.com wrote:
> >...  I don't think that I can turn in your answer ..
[quoted text clipped - 20 lines]
>
> Message posted via JavaKB.comhttp://www.javakb.com/Uwe/Forums.aspx/java-general/200711/1

Thanks again.  I am on a very, very basic level of Java.  Honestly, I
don't even consider myself as even being on a level yet.  But anyhow,
I had the two comparisons in there because it was the only way that I
could think of to make it exit the loop as soon as the billType "done"
was entered.  Most of that code was already written in our assignment
and we just had to add the loop.

Is there a good webpage that's designed for beginners or is real easy
to understand and make use of.  I can see myself really liking Java
but am a bit cloudy as I'm just starting off.  Any favorites you'd
like to share?
Thanks,
David
Roedy Green - 30 Nov 2007 07:35 GMT
>if(billType != "done")

that is not how you compare strings.

See http://mindprod.com/jgloss/string.html
Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

Roedy Green - 30 Nov 2007 07:37 GMT
>String stringAmount;    // String version of bill amount.
>        double billAmount;    // Amount of the bill.
>        double sum = 0;     // Accumulates sum of bills.

Don't define local variables any sooner than you have to.  Define them
at first use, and in the innermost nest possible.
Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

Roedy Green - 30 Nov 2007 07:44 GMT
>do
>        {
[quoted text clipped - 18 lines]
>
>        }while(billType != "done");

Try rearranging your loop so there is only one "done" test.  Hint
"break" out of while(true) is a way of stopping a loop too.
Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

DBJohnston0104@gmail.com - 01 Dec 2007 13:50 GMT
On Nov 30, 2:44 am, Roedy Green <see_webs...@mindprod.com.invalid>
wrote:
> On Wed, 28 Nov 2007 18:34:52 -0800 (PST), DBJohnston0...@gmail.com
> wrote, quoted or indirectly quoted someone who said :
[quoted text clipped - 29 lines]
>
> - Show quoted text -

Thanks for all the help!  I've re-downloaded the source file for the
assignment and, using what I've learned here, rewrote the code...  and
it works.  It's pretty exciting to be "officially" learning a
programming language.  I do quite a bit of VBA in MS Office apps but
it's all been self-taught so this is a change for me.  Anyway...
Thanks again!
David


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.