Can I have an if statement inside a while loop? or something similar?
So i am writing a code to display the windchill temperature, the user enters a temp and windspeed and they are given the windchill temp. The thing is they have to enter a temp within -58F and 41F, I want it to make them keep entering a temp until it is valid, right now it just prompts them to re-enter once then if they enter an invlaid again it still works...
heres the code
Code java:
import javax.swing.JOptionPane;
public class Pg125 {
public static void main(String[] args) {
//Input and Output= Dialog
String temp = JOptionPane.showInputDialog("Enter a temperature within -58F and 41F: ");
Double temp1 = Double.parseDouble(temp);
//temp if
if(temp1 < -58 || temp1 > 41){
JOptionPane.showInputDialog("The temperature " + temp1 + " is invalid. Please enter a valid temperature");
}//end of temp if
String windspeed = JOptionPane.showInputDialog("Enter a wind speed of 2 or greater: ");
Double windspeed1 = Double.parseDouble(windspeed);
//windspeed if
if(windspeed1 < 2) {
JOptionPane.showMessageDialog(null, "The windspeed " + windspeed1 + " is invalid. Please click cancel and enter a valid windspeed");
}//end of windspeed if
Double windchill = 35.74 + 0.6215*temp1 - 35.75*Math.pow(windspeed1, 0.16) + 0.4275*temp1*Math.pow(windspeed1, 0.16);
//wind-chill if
if(temp1 > -58 || temp1 < 41 && windspeed1 >= 2){
JOptionPane.showMessageDialog(null, "The wind-chill temperature is " + windchill);
}//end of wind-chill if
}
}
I tried just changing the if into a while, but it just keeps asking them to enter a valid one even if it is valid... thanks.
Re: Can I have an if statement inside a while loop? or something similar?
A basic do-while loop is one way to get something done to satisfy your conditions. The layout may resemble this:
do {
some thing correctly
} while ( something was done wrong)
If the something is done correctly the first time, the "loop" will not repeat.
I see you have:
(temp1 > -58 || temp1 < 41 && windspeed1 >= 2)
before your output. I just want to mention that if you verify the input as you get it, you don't need to verify it again before you output. This is not always the case, but in this specific case the values are never modified.
Re: Can I have an if statement inside a while loop? or something similar?
what do you mean "something correctly" and "something done wrong"? Could you provide an example please? Thanks for your response
Re: Can I have an if statement inside a while loop? or something similar?
Quote:
Originally Posted by
ColeTrain
what do you mean "something correctly" and "something done wrong"? Could you provide an example please? Thanks for your response
I basically handed you an answer (of the many possible). Read over this link and utilize your favorite search engine on keywords "java loops".
If you have questions after seeing the wealth of information, feel free to ask.
Good luck with your project!