While statement

Discussion in 'Java' started by geletine, Jan 23, 2006.

  1. geletine

    geletine Guest

    With the following piece of code, i would like to convert pounds to
    dollars and then print to the screen, and then the program will ask me
    if i want to convert more pounds to dollars, but what the program does
    is asks for the pounds and prints the conversion and then ask if i
    would like to convert more pounds, but unfortunately it does not ask me
    again, i presume i am not understanding how the while loops works.
    here is the example i am trying out.
    the code was translated from pseudocode to java syntax.


    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    public class currencyc
    {
    public static void main (String args [])throws IOException
    {
    double pounds,dollars;
    String money, answer,y;

    answer = "y";


    while (answer == "y")
    {

    money = JOptionPane.showInputDialog (" how many pounds do you
    want to conver
    t ? ");
    pounds = Double.parseDouble(money);
    dollars = pounds * 1.44;
    System.out.println(dollars);
    answer = JOptionPane.showInputDialog (" would you like another
    go , yes/no?
    ");
    }
    }
    }
     
    geletine, Jan 23, 2006
    #1
    1. Advertising

  2. geletine

    Jeroen V. Guest

    You are comparing references to string instances where you should
    compare the actual string instances

    while(answer == "y") should be while(answer.equals("y"))


    geletine wrote:
    > With the following piece of code, i would like to convert pounds to
    > dollars and then print to the screen, and then the program will ask me
    > if i want to convert more pounds to dollars, but what the program does
    > is asks for the pounds and prints the conversion and then ask if i
    > would like to convert more pounds, but unfortunately it does not ask me
    > again, i presume i am not understanding how the while loops works.
    > here is the example i am trying out.
    > the code was translated from pseudocode to java syntax.
    >
    >
    > import java.awt.*;
    > import java.awt.event.*;
    > import javax.swing.*;
    > import java.io.*;
    > public class currencyc
    > {
    > public static void main (String args [])throws IOException
    > {
    > double pounds,dollars;
    > String money, answer,y;
    >
    > answer = "y";
    >
    >
    > while (answer == "y")
    > {
    >
    > money = JOptionPane.showInputDialog (" how many pounds do you
    > want to conver
    > t ? ");
    > pounds = Double.parseDouble(money);
    > dollars = pounds * 1.44;
    > System.out.println(dollars);
    > answer = JOptionPane.showInputDialog (" would you like another
    > go , yes/no?
    > ");
    > }
    > }
    > }
    >
     
    Jeroen V., Jan 23, 2006
    #2
    1. Advertising

  3. geletine

    zero Guest

    "geletine" <> wrote in news:1138041018.041233.9440
    @z14g2000cwz.googlegroups.com:

    >
    > import java.awt.*;
    > import java.awt.event.*;
    > import javax.swing.*;
    > import java.io.*;


    Jeroen already gave you the answer to your problem, but I'd like to
    offer some additional advice.

    What classes of package java.awt are you using? Examine all your import
    statements, and see if you really need them. Don't import packages you
    don't use. And when you only need one or two classes from a package,
    import only those classes, not the whole package.

    > public class currencyc


    For readability, you should always follow the convention of starting
    class names with a capital letter.

    > public static void main (String args [])throws IOException


    Where is that IOException being thrown? Which statement in your main
    method throws it? You shouldn't have a method throw an exception unless
    it actually has a throw statement, or if a method it uses throws one.
    Also, main should never throw an exception. Catch any exceptions that
    are thrown inside your main method, and handle them gracefully.

    > double pounds,dollars;
    > String money, answer,y;


    Avoid using package access when private will suffice. In particular,
    use "private double pounds". Even better, when you only need a variable
    in one method, declare it as local in that method.
    Where do you use the y variable? Don't declare variables you don't
    need.

    > pounds = Double.parseDouble(money);


    One of the 10 commandments of C/C++ is "always check your input". I
    would say this goes for every programming language. If the user enters
    "hello" into the input dialog, you should be able to recover from this.
    If your course hasn't covered exceptions yet, ignore this comment.

    Good luck with your studies, and have fun :)
     
    zero, Jan 23, 2006
    #3
  4. geletine

    geletine Guest

    Thank you for your explanation, i thought i need to use awt libaries
    too, where as swing will suffice?
    public static void main (String args [])throws IOException
    i used that to catch any input output errors, hence i imported the
    import output libary.
    when i say catch, ive heard of the catch and try methods, but i presume
    that line covers a whole libary of errors so the need for me to specify
    what to catch in such a small program is not needed.
    i have not learnt private access at the moment, i may guess that
    private means that no other classes can acces this particular class, in
    this program public is not a problem for me.
    the y variable is for the user if they want to repeat the conversion,
    otherwise what would signify a repeat of the loop?
    lastly i have not included error checking as you lastly stated, at the
    moment i am only learning loops.





    zero wrote:

    > "geletine" <> wrote in news:1138041018.041233.9440
    > @z14g2000cwz.googlegroups.com:
    >
    > >
    > > import java.awt.*;
    > > import java.awt.event.*;
    > > import javax.swing.*;
    > > import java.io.*;

    >
    > Jeroen already gave you the answer to your problem, but I'd like to
    > offer some additional advice.
    >
    > What classes of package java.awt are you using? Examine all your import
    > statements, and see if you really need them. Don't import packages you
    > don't use. And when you only need one or two classes from a package,
    > import only those classes, not the whole package.
    >
    > > public class currencyc

    >
    > For readability, you should always follow the convention of starting
    > class names with a capital letter.
    >
    > > public static void main (String args [])throws IOException

    >
    > Where is that IOException being thrown? Which statement in your main
    > method throws it? You shouldn't have a method throw an exception unless
    > it actually has a throw statement, or if a method it uses throws one.
    > Also, main should never throw an exception. Catch any exceptions that
    > are thrown inside your main method, and handle them gracefully.
    >
    > > double pounds,dollars;
    > > String money, answer,y;

    >
    > Avoid using package access when private will suffice. In particular,
    > use "private double pounds". Even better, when you only need a variable
    > in one method, declare it as local in that method.
    > Where do you use the y variable? Don't declare variables you don't
    > need.
    >
    > > pounds = Double.parseDouble(money);

    >
    > One of the 10 commandments of C/C++ is "always check your input". I
    > would say this goes for every programming language. If the user enters
    > "hello" into the input dialog, you should be able to recover from this.
    > If your course hasn't covered exceptions yet, ignore this comment.
    >
    > Good luck with your studies, and have fun :)
     
    geletine, Jan 23, 2006
    #4
  5. geletine

    Oliver Wong Guest

    "zero" <> wrote in message
    news:Xns9754CABFC3434zerothishi@195.130.132.70...
    >
    > Also, main should never throw an exception. Catch any exceptions that
    > are thrown inside your main method, and handle them gracefully.


    I disagree with this. If the main method encounters an exception that it
    cannot handle in any reasonable way, it should throw that exception.

    - Oliver
     
    Oliver Wong, Jan 23, 2006
    #5
  6. geletine

    Oliver Wong Guest

    "geletine" <> wrote in message
    news:...
    >
    > the y variable is for the user if they want to repeat the conversion,
    > otherwise what would signify a repeat of the loop?


    In the code you posted earlier in this thread, the variable called "y"
    is never used. You stored the user's answer in a variabe called "answer".

    - Oliver
     
    Oliver Wong, Jan 23, 2006
    #6
  7. geletine

    zero Guest

    "geletine" <> wrote in
    news::

    > Thank you for your explanation, i thought i need to use awt libaries
    > too, where as swing will suffice?
    > public static void main (String args [])throws IOException
    > i used that to catch any input output errors, hence i imported the
    > import output libary.
    > when i say catch, ive heard of the catch and try methods, but i
    > presume that line covers a whole libary of errors so the need for me
    > to specify what to catch in such a small program is not needed.
    > i have not learnt private access at the moment, i may guess that
    > private means that no other classes can acces this particular class,
    > in this program public is not a problem for me.
    > the y variable is for the user if they want to repeat the conversion,
    > otherwise what would signify a repeat of the loop?
    > lastly i have not included error checking as you lastly stated, at the
    > moment i am only learning loops.
    >


    You only need to import the libraries you actually use. In this
    program, you don't use any awt classes, and only JOptionPane from swing.
    So, all you need is:

    import javax.swing.JOptionPane;

    As for the IOException, you don't need it. You'll only need it when you
    use actual stream I/O, like files or sockets. Until you learn about
    exceptions, just stay away from the altogether. They will only confuse
    you and make learning the rest harder.

    Since you haven't learned about access modifiers I assume your course
    starts with structural language elements (if/else, while, for, methods),
    and OO principles will come later. I feel quite strongly about this,
    but as student you probably can't do much about it. IMO teaching
    structural programming first is completely and utterly wrong. It may be
    historically correct, but not from an educational standpoint.

    Anyway that would be a discussion I'd need to have with your teacher,
    not you. private indeed means that other classes can't use that
    variable. It is a fundamental concept of OOP to keep the privileges as
    tight as possible. But if you haven't learned this yet, just ignore it.

    Lastly, you seem to be confusing the variable y with the String "y".
    You are not using variable y declared in

    String y;

    You are however using the string "y", in the loop condition. But this
    is not the variable y.
     
    zero, Jan 23, 2006
    #7
  8. geletine

    zero Guest

    "Oliver Wong" <> wrote in
    news:e2aBf.124818$6K2.33604@edtnps90:

    >
    > "zero" <> wrote in message
    > news:Xns9754CABFC3434zerothishi@195.130.132.70...
    >>
    >> Also, main should never throw an exception. Catch any exceptions
    >> that are thrown inside your main method, and handle them gracefully.

    >
    > I disagree with this. If the main method encounters an exception
    > that it
    > cannot handle in any reasonable way, it should throw that exception.
    >
    > - Oliver
    >
    >
    >


    In programming there are no absolutes of course. If I say "never", I
    actually mean "never unless you are an experienced programmer and have a
    compelling reason".

    In general though, I think there is little use in main throwing an
    exception. It would only be useful if the main method is called
    programmatically, which is not typically the case.
     
    zero, Jan 23, 2006
    #8
  9. geletine

    Oliver Wong Guest

    "zero" <> wrote in message
    news:Xns9754D14DDD547zerothishi@195.130.132.70...
    > "Oliver Wong" <> wrote in
    > news:e2aBf.124818$6K2.33604@edtnps90:
    >
    >>
    >> "zero" <> wrote in message
    >> news:Xns9754CABFC3434zerothishi@195.130.132.70...
    >>>
    >>> Also, main should never throw an exception. Catch any exceptions
    >>> that are thrown inside your main method, and handle them gracefully.

    >>
    >> I disagree with this. If the main method encounters an exception
    >> that it
    >> cannot handle in any reasonable way, it should throw that exception.

    >
    > In programming there are no absolutes of course. If I say "never", I
    > actually mean "never unless you are an experienced programmer and have a
    > compelling reason".
    >
    > In general though, I think there is little use in main throwing an
    > exception. It would only be useful if the main method is called
    > programmatically, which is not typically the case.


    Maybe I am biased, because I was specifically in the situation of
    wanting to call the main method of some 3rd party code, and wanted to handle
    the exception situation it encountered. The 3rd party code would catch the
    exception and then call system.exit(-1), thus killing my code as well as its
    own.

    I also don't like code which catches exceptions, and silently ignores
    them. Or that simply prints that some exception has occured without
    providing a stack trace.

    My debugger will automatically pause program execution when it detects
    an uncaught exception; but if something catches the exception, my debugger
    assumes that the exception was correctly handled and so doesn't pause
    program execution. So when you're debugging someone else's code, and you
    just see "Exception occured" on standard error, you have to step through a
    hell of a lot of code trying to locate what exception is getting thrown and
    where.

    - Oliver
     
    Oliver Wong, Jan 23, 2006
    #9
  10. geletine

    Roedy Green Guest

    On 23 Jan 2006 10:30:18 -0800, "geletine" <>
    wrote, quoted or indirectly quoted someone who said :

    > answer = JOptionPane.showInputDialog (" would you like another
    >go , yes/no?
    >");

    try inserting System.out.println( "{" + answer + "}" );

    just after that line.
    --
    Canadian Mind Products, Roedy Green.
    http://mindprod.com Java custom programming, consulting and coaching.
     
    Roedy Green, Jan 23, 2006
    #10
  11. geletine

    geletine Guest

    i took out the variable y and added
    System.out.println( "{" + answer + "}" );

    and i recieved
    allix@allix:~/javafiles$ javac currencyc.java
    currencyc.java:15: variable answer might not have been initialized
    while (answer.equals ("y"))
    ^
    1 error
    allix@allix:~/javafiles$

    so from my understanding the variable y was inialised
     
    geletine, Jan 23, 2006
    #11
  12. geletine

    Roedy Green Guest

    On 23 Jan 2006 12:46:41 -0800, "geletine" <>
    wrote, quoted or indirectly quoted someone who said :

    >currencyc.java:15: variable answer might not have been initialized
    >while (answer.equals ("y"))
    > ^
    >1 error


    You have jostled something since your original. Please repost your
    latest code.
    --
    Canadian Mind Products, Roedy Green.
    http://mindprod.com Java custom programming, consulting and coaching.
     
    Roedy Green, Jan 23, 2006
    #12
  13. geletine

    geletine Guest

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    public class currencyc
    {
    public static void main (String args [])throws IOException
    {
    double pounds,dollars;
    String money, answer;





    while (answer.equals ("y"))
    {

    money = JOptionPane.showInputDialog (" how many pounds do you
    want to convert ? ");
    pounds = Double.parseDouble(money);
    dollars = pounds * 1.44;
    System.out.println(dollars);
    answer = JOptionPane.showInputDialog (" would you like another
    go , yes/no? " );
    System.out.println( "{" + answer + "}" );
    }
    }
    }
    ~
     
    geletine, Jan 23, 2006
    #13
  14. geletine

    Oliver Wong Guest

    "geletine" <> wrote in message
    news:...
    > import java.awt.*;
    > import java.awt.event.*;
    > import javax.swing.*;
    > import java.io.*;
    > public class currencyc
    > {
    > public static void main (String args [])throws IOException
    > {
    > double pounds,dollars;
    > String money, answer;
    >
    >
    >
    >
    > while (answer.equals ("y"))
    > {
    >
    > money = JOptionPane.showInputDialog (" how many pounds do you
    > want to convert ? ");
    > pounds = Double.parseDouble(money);
    > dollars = pounds * 1.44;
    > System.out.println(dollars);
    > answer = JOptionPane.showInputDialog (" would you like another
    > go , yes/no? " );
    > System.out.println( "{" + answer + "}" );
    > }
    > }
    > }
    > ~
    >


    If you know how, change your while loop to a do loop.

    Otherwise, change the line near the top that says:

    <code>
    String money, answer;
    </code>

    to the following:

    <code>
    String money, answer = "y";
    </code>

    - Oliver
     
    Oliver Wong, Jan 23, 2006
    #14
  15. geletine

    Roedy Green Guest

    On 23 Jan 2006 13:26:34 -0800, "geletine" <>
    wrote, quoted or indirectly quoted someone who said :

    >String money, answer;
    >
    >
    >
    >
    >
    >while (answer.equals ("y"))


    What is the value of answer the first time through the while? You
    inadvertently removed a crucial line of code.
    --
    Canadian Mind Products, Roedy Green.
    http://mindprod.com Java custom programming, consulting and coaching.
     
    Roedy Green, Jan 23, 2006
    #15
  16. geletine

    Roedy Green Guest

    On Mon, 23 Jan 2006 22:11:07 GMT, "Oliver Wong" <>
    wrote, quoted or indirectly quoted someone who said :

    >
    > If you know how, change your while loop to a do loop.


    see http://mindprod.com/jgloss/jcheat.html
    --
    Canadian Mind Products, Roedy Green.
    http://mindprod.com Java custom programming, consulting and coaching.
     
    Roedy Green, Jan 23, 2006
    #16
  17. geletine

    geletine Guest

    I am not totally confident with do loops at the moment.
    do they allow mutliple choice?
    I know about the if ,else and case selection construction, its just i
    have problems finding a solution to the following:-

    the program must ask the user for a integer value and print the sum of
    all even between 1 and the imputed value inclusive, as as well as the
    sum off all the odd numbers. lastly the program should print the
    inputed value some of the eben integers and sum of odd integers.

    here is my pseudocode

    read users imputed integer numer

    start loop
    find wheather number is even
    if (even)
    find out all the odd and even numbers and find the sum off odd and even
    numbers
    print the number entered, that its even , the odd and even numbers and
    the sum of them
    else
    number is odd and also find odd and even numbers and find the sum off
    odd and even numbers
    print the number entered, that its odd , the odd and even numbers and
    the sum of them
    end loop

    and lastly here is my attempt of the java code

    import java.io.*;
    public class odd
    {
    public static void main(String args[] )throws IOException
    {

    int number,oddnum,evennum,sumeven,sumodd;
    String inData;
    BufferedReader stgin = new BufferedReader ( new InputStreamReader
    (System.in ) )
    ;
    evenum = 0;
    oddnumber = 0;

    System.out.println ("Enter a number please?");
    inData = stgin.readLine();
    number = Integer.parseInt ( inData );

    while if (number%2 == 0)// too test wheather number is even or odd

    sumeven = number++;
    {
    number = evenumber + Integer.toString(sumeven)+ " ";

    }
    System.out.println(" The even numbers " + sumeven);

    else
    sumodd = number++;
    {
    number = oddnumber + Integer.toString(sumodd)+ " ";

    System.out.println("the odd numbers are " + sumodd);
    }
    }
    }

    the code does not work, perhaps my pseudocode is completly wrong to
    start off with all my java code is not corisponding to what the
    psedocode is.
     
    geletine, Jan 24, 2006
    #17
  18. geletine

    Oliver Wong Guest

    "geletine" <> wrote in message
    news:...
    >I am not totally confident with do loops at the moment.
    > do they allow mutliple choice?
    > I know about the if ,else and case selection construction, its just i
    > have problems finding a solution to the following:-
    >
    > the program must ask the user for a integer value and print the sum of
    > all even between 1 and the imputed value inclusive, as as well as the
    > sum off all the odd numbers. lastly the program should print the
    > inputed value some of the eben integers and sum of odd integers.


    Your have a lot of spelling mistakes, but you seem to have a strong
    grasp of grammar and phrase structure, so it seems to me that you're a
    native English speaker, but just not too careful when you type.

    When programming, you have to be a very careful. The tiniest typo in a
    program will usually completely alter that program's behaviour. I mention
    this because when I read your last sentence, I was rather confused: "lastly
    the program should print the inputed value some of the eben integers and sum
    of odd integers." I could guess that "eben" meant "even", but it took me a
    long time to realize what you meant by "print some of the even integers".
    I'm guessing you mean "sum", not "some".

    See, some people might not have caught that, and then have been unable
    to help you out. Anyway, just pointing that out. Now on to the real meat of
    the problem...

    >
    > here is my pseudocode
    >
    > read users imputed integer numer
    >
    > start loop
    > find wheather number is even
    > if (even)
    > find out all the odd and even numbers and find the sum off odd and even
    > numbers
    > print the number entered, that its even , the odd and even numbers and
    > the sum of them
    > else
    > number is odd and also find odd and even numbers and find the sum off
    > odd and even numbers
    > print the number entered, that its odd , the odd and even numbers and
    > the sum of them
    > end loop


    It sounds like your pseudocode will more or less actually do what the
    program is supposed to do. There's one big structural issue, though. You
    mention "start loop" and "end loop", but you don't say what the conditions
    are for continuing to loop, or when to break out of the loop. Does the
    program just keep on doing the above forever, or what?

    Also note that you have duplicate code in both branches of your if
    statement. When you have a structure like this:

    <pseudocode>
    if (some condition) {
    do A;
    do B;
    } else {
    do A;
    do C;
    }
    </pseudocode>

    You can usually[*] extract the common code out, like this:

    <pseudocode>
    do A;
    if (some condition) {
    do B;
    } else {
    do C;
    }
    </pseudocode>

    My other comment is that your pseudocode is very high level. It doesn't
    say *how* you plan on finding all the even numbers, or getting the sum of
    them, for example.

    >
    > and lastly here is my attempt of the java code
    >
    > import java.io.*;
    > public class odd
    > {
    > public static void main(String args[] )throws IOException
    > {
    >
    > int number,oddnum,evennum,sumeven,sumodd;
    > String inData;
    > BufferedReader stgin = new BufferedReader ( new InputStreamReader
    > (System.in ) )
    > ;
    > evenum = 0;
    > oddnumber = 0;
    >
    > System.out.println ("Enter a number please?");
    > inData = stgin.readLine();
    > number = Integer.parseInt ( inData );
    >
    > while if (number%2 == 0)// too test wheather number is even or odd
    >
    > sumeven = number++;
    > {
    > number = evenumber + Integer.toString(sumeven)+ " ";
    >
    > }
    > System.out.println(" The even numbers " + sumeven);
    >
    > else
    > sumodd = number++;
    > {
    > number = oddnumber + Integer.toString(sumodd)+ " ";
    >
    > System.out.println("the odd numbers are " + sumodd);
    > }
    > }
    > }
    >
    > the code does not work, perhaps my pseudocode is completly wrong to
    > start off with all my java code is not corisponding to what the
    > psedocode is.
    >


    Yeah, there's a lot of problems with this code. But rather than fixing
    the code directly, you should probably go back to the pseudocode and address
    the issues I mentioned above; that is: (1) Specify what the condition is for
    the loop (2) Add more low-level detail.

    - Oliver

    [*] I say "usually", because one situation where it could fail is if testing
    the condition might have side-effects that affect the subroutine "do A". You
    should generally write your if-statements so that the conditions do NOT
    cause any side effects, so this should be a very rare exceptional case.
     
    Oliver Wong, Jan 24, 2006
    #18
  19. geletine

    geletine Guest

    sorry , when i type too quickly i make elementary spelling mistakes.
    indeed you decyphered what i meant.

    The program is not intented to loop, i believe the loop is essential to
    the program.

    I obviously did not think what i was doing when duplicating code...

    i wrote the pseudocode on a very abstract level, purposely taking out
    the calculations, which is incorrect as you rightly point out. I need
    to change it to resemble working code, without getting into any
    particular programming language syntax.

    I will work on everything that you have mentioned, and post a little
    later with hopefully some positive outcome.
     
    geletine, Jan 24, 2006
    #19
  20. geletine

    Roedy Green Guest

    On 24 Jan 2006 08:03:48 -0800, "geletine" <>
    wrote, quoted or indirectly quoted someone who said :

    >I am not totally confident with do loops at the moment.
    >do they allow mutliple choice?


    They have nothing to do with choice. They simply keep going as long as
    some condition is true. For loops in contrast repeat a counted number
    of times.

    do while executes the loop at least once. Plain while tests before it
    starts so may execute 0 times.

    for sample code see http://mindprod.com/jgloss/jcheat.html#LOOPS
    --
    Canadian Mind Products, Roedy Green.
    http://mindprod.com Java custom programming, consulting and coaching.
     
    Roedy Green, Jan 24, 2006
    #20
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
    3
    Views:
    807
  2. Jay McGavren
    Replies:
    11
    Views:
    1,144
    Alan Krueger
    Jan 16, 2006
  3. tedsuzman
    Replies:
    2
    Views:
    7,094
    Michel Claveau, résurectionné d'outre-bombe inform
    Jul 21, 2004
  4. Ted
    Replies:
    1
    Views:
    470
    Duncan Booth
    Jul 22, 2004
  5. Replies:
    21
    Views:
    1,060
    Giannis Papadopoulos
    Aug 2, 2005
Loading...

Share This Page