Java Forum / General / January 2006
While statement
geletine - 23 Jan 2006 18:30 GMT 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. - 23 Jan 2006 18:39 GMT You are comparing references to string instances where you should compare the actual string instances
while(answer == "y") should be while(answer.equals("y"))
> 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 [quoted text clipped - 33 lines] > } > } zero - 23 Jan 2006 18:55 GMT "geletine" <adaviscg1@hotmail.com> 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 - 23 Jan 2006 19:09 GMT 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.
> "geletine" <adaviscg1@hotmail.com> wrote in news:1138041018.041233.9440 > @z14g2000cwz.googlegroups.com: [quoted text clipped - 42 lines] > > Good luck with your studies, and have fun :-) Oliver Wong - 23 Jan 2006 19:24 GMT > 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
zero - 23 Jan 2006 19:31 GMT > Thank you for your explanation, i thought i need to use awt libaries > too, where as swing will suffice? [quoted text clipped - 11 lines] > 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.
Oliver Wong - 23 Jan 2006 19:22 GMT > 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
zero - 23 Jan 2006 19:34 GMT >> Also, main should never throw an exception. Catch any exceptions >> that are thrown inside your main method, and handle them gracefully. [quoted text clipped - 4 lines] > > - 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.
Oliver Wong - 23 Jan 2006 20:15 GMT >>> Also, main should never throw an exception. Catch any exceptions >>> that are thrown inside your main method, and handle them gracefully. [quoted text clipped - 10 lines] > 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
Chris Smith - 24 Jan 2006 22:15 GMT > 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". I agree with Oliver that this is the wrong default in this case. When writing code that needs to conform to a specified use of stdout and stderr, you might need to catch exceptions in main. Similarly, if you have an error reporting infrastructure such as a logging package that sends email to the software development team, then you have a good reason to catch exceptions (and, likely, to rethrow them when you're done). Otherwise, just let them be thrown.
> In general though, I think there is little use in main throwing an > exception. ... except that it's an easy way to be sure that a complete error report is available when it occurs, without doing it yourself.
 Signature www.designacourse.com The Easiest Way To Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer MindIQ Corporation
Roedy Green - 23 Jan 2006 20:27 GMT > answer = JOptionPane.showInputDialog (" would you like another >go , yes/no? >"); try inserting System.out.println( "{" + answer + "}" );
just after that line.
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
geletine - 23 Jan 2006 20:46 GMT 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
Roedy Green - 23 Jan 2006 20:59 GMT >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.
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
geletine - 23 Jan 2006 21:26 GMT 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 + "}" ); } } } ~
Oliver Wong - 23 Jan 2006 22:11 GMT > import java.awt.*; > import java.awt.event.*; [quoted text clipped - 22 lines] > } > ~ 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
Roedy Green - 23 Jan 2006 22:59 GMT > If you know how, change your while loop to a do loop. see http://mindprod.com/jgloss/jcheat.html
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
Roedy Green - 23 Jan 2006 22:33 GMT >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.
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
geletine - 24 Jan 2006 16:03 GMT 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.
Oliver Wong - 24 Jan 2006 16:31 GMT >I am not totally confident with do loops at the moment. > do they allow mutliple choice? [quoted text clipped - 5 lines] > 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 > [quoted text clipped - 13 lines] > 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 > [quoted text clipped - 38 lines] > 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.
geletine - 24 Jan 2006 16:50 GMT 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.
Roedy Green - 24 Jan 2006 18:46 GMT >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
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
Tom Leylan - 24 Jan 2006 23:59 GMT "geletine" <adaviscg1@hotmail.com> wrote...
> start loop > find wheather number is even [quoted text clipped - 9 lines] > the sum of them > end loop Hey how's things? Let me give you the big picture... I'm big on painting the big picture before working on the details.
Consider the pseudocode you're written already converted to Java, what do you have? You have a program that asks for input, compares a value, sums the numbers and prints the values. Frankly you will never need that program again. :-)
Consider instead what you would have if you had a "NumberInfo" class that had methods that corresponded to all sorts of things you might need to compute. So you would provide a number (probably input from somewhere but the method doesn't care) and it would return say... sumEvenValues() and sumOddValues(). Notice these methods wouldn't output them it would just compute them and return them. Then you could create a program that asks for input, reads input from a file or has a value hardcoded into it and it could output the value to the screen, to a printer or to another file.
And here is the big plus... when you need computeAverage() you would simply add that method. This wouldn't destroy or in any way alter your current program but it would provide another functionality which somebody (perhaps you) could use at some point. The system could "grow."
In short, break a problem up into little problems, program solutions to those little problems and assemble those solutions into one that satisfies your original problem.
Hope this helps, Tom
geletine - 26 Jan 2006 18:08 GMT I have had a go at the last task and i confident i am progressing, but i am not sure quite there yet here is the code
import java.io.*; public class odd { public static void main(String args[] )throws IOException {
int number,oddnum,evenum,sumeven,sumodd; String inData; BufferedReader stgin = new BufferedReader ( new InputStreamReader (System.in ) ); number = 0; evenum = 0; oddnum = 0; sumeven = 0; sumodd = 0;
if while (number%2 == 0) { System.out.println ("Enter a number please?") inData = stgin.readLine() number = Integer.parseInt ( inData ) number = evenum; sumeven = sumeven + evenum; {
else { System.out.println ("Enter a number please?") inData = stgin.readLine() number = Integer.parseInt ( inData ) number = oddnum; sumodd = sumodd + oddnum; }
System.out.println ( sumeven); System.out.println( sumodd);
} }
Oliver Wong - 26 Jan 2006 20:22 GMT >I have had a go at the last task and i confident i am progressing, but > i am not sure quite there yet [quoted text clipped - 39 lines] > } > } I just have two somewhat long comments:
(1) I didn't see your revised pseudocode. Maybe you posted it and it never reached my newsserver, in which case just let me know and I'll use GoogleGroups or something to find it. Otherwise, it's not clear that you've a fully devised a plan for solving this problem. If you don't have a plan, then you're just typing blindly, and there's no real reason to believe that the code you write down would solve the problem you're trying to solve. You should be confident that your plan will work before you start typing in code, and one way to do that is to write out pseudo code and go through it and check that the pseudocode fills all the requirements of the problem.
(2) In my personal opinion, if you're confused or kind of lost in your program, it's better to give your variable names which are too long, as opposed to names which are too short. Giving your variables highly descriptive names -- that reveal what their contents are and their purpose -- will make it a lot easier to spot mistakes in the logic of your code. As you get more comfortable programming, you get lazier; since it takes a long time to type in a long name, you'll start to shorten the names. But when you want clarity, go for longer names.
For example, you have a variable called "number", which is somewhat vague. A person's age happens to be a number, so does this variable contain someone's age? Perhaps it contains someone's social security number? Or does it contain the number of times something should happen? Or something else?
Here, it looks like you're using that variable to store the number the user entered in. If that's the case, you might name the variable "numberThatTheUserEnteredIn". That's a bit better, but even then, it's not clear what is the meaning of the number that the user entered in.
Let's say your writing some sort of penguin simulation game, SimPenguin, and you prompt the user "How many penguins would you like to simulate?" In this case, a better name than either "number" or "numberThatTheUserEnteredIn" is "numberOfPenguinsToSimulate". This new name, "numberOfPenguinsToSimulate", gives a clear indication of what kind of value is stored in the variable, and what it should be used for.
- Oliver
Roedy Green - 26 Jan 2006 23:38 GMT > if while (number%2 == 0) > { [quoted text clipped - 13 lines] > sumodd = sumodd + oddnum; > } note how there are 3 lines the same in both branches of the if? Factor that out of the if so it appears only once.
Also you want to do your even-odd test on the most recently-entered number, not the previous one.
 Signature Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching.
geletine - 27 Jan 2006 21:17 GMT A collegue helped me complete the program. I hope its clear.
Here is the code and a sample of it working
import java.io.*; public class odd { public static void main(String args[] )throws IOException {
int number,sumeven,sumodd,storage; String inData,evenum,oddnum; BufferedReader stgin = new BufferedReader ( new InputStreamReader (System.in ) ); sumeven = 0; sumodd = 0; evenum = " "; oddnum = " "; storage = 0;
System.out.println ("Enter a number please?"); inData = stgin.readLine(); number = Integer.parseInt ( inData );
while (storage <= number) { if ( storage %2 == 0) { sumeven = sumeven + storage; evenum=evenum + Integer.toString (storage) + " "; }
else { sumodd = sumodd + storage; oddnum = oddnum+Integer.toString (storage) + " "; } storage = storage + 1; }
System.out.println (" Sum of even is " + sumeven ); System.out.println (" Sum of odd is "+ sumodd ); System.out.println (" odd numbers are " + oddnum); System.out.println (" even numbers are " + evenum); } }
allix@allix:~/javafiles$ java odd Enter a number please? 10 Sum of even is 30 Sum of odd is 25 odd numbers are 1 3 5 7 9 even numbers are 0 2 4 6 8 10 allix@allix:~/javafiles$ java odd Enter a number please? 25 Sum of even is 156 Sum of odd is 169 odd numbers are 1 3 5 7 9 11 13 15 17 19 21 23 25 even numbers are 0 2 4 6 8 10 12 14 16 18 20 22 24
Free MagazinesGet 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 ...
|
|
|