While statement

G

geletine

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?
");
}
}
}
 
J

Jeroen V.

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

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

zero

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 :)
 
G

geletine

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.




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 :)
 
O

Oliver Wong

zero said:
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
 
O

Oliver Wong

geletine said:
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
 
Z

zero

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.
 
Z

zero

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.
 
O

Oliver Wong

zero said:
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
 
R

Roedy Green

answer = JOptionPane.showInputDialog (" would you like another
go , yes/no?
");
try inserting System.out.println( "{" + answer + "}" );

just after that line.
 
G

geletine

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
 
R

Roedy Green

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.
 
G

geletine

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 + "}" );
}
}
}
~
 
O

Oliver Wong

geletine said:
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
 
R

Roedy Green

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.
 
G

geletine

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.
 
O

Oliver Wong

geletine said:
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.
 
G

geletine

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.
 
R

Roedy Green

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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top