• Some users have recently had their accounts hijacked. It seems that the now defunct EVGA forums might have compromised your password there and seems many are using the same PW here. We would suggest you UPDATE YOUR PASSWORD and TURN ON 2FA for your account here to further secure it. None of the compromised accounts had 2FA turned on.
    Once you have enabled 2FA, your account will be updated soon to show a badge, letting other members know that you use 2FA to protect your account. This should be beneficial for everyone that uses FSFT.

adding a loop to a program

ndruw

Limp Gawd
Joined
Mar 7, 2006
Messages
246
I wrote this little program to convert celsius to fahrenheit and back in java (I'm teaching myself in my spare time, but I want to get it to restart (loop?) every time its done until someone types 'quit' into the reader. How would I do this?

// Name: Convert (Fahrenheit <-->
// Celsius)
// Description:Convert degrees Celsius
// to degrees Fahrenheit, and vice-versa.
// By: Andrew


import TerminalIO.KeyboardReader;


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


{
KeyboardReader reader = new KeyboardReader();

int choice = reader.readInt("If you would like to convert from Fahrenheit to Celsius, enter 1. \n"
+ "For Celsius to Fahrenheit, enter 2. ");

if (choice == 1) {

double fahrenheit = reader.readDouble("Degrees fahrenheit: ");
double celsius = (fahrenheit - 32.0) * (5.0 / 9.0);
System.out.println(+ fahrenheit + " degrees Fahrenheit = " + celsius + " degrees Celcius.");
}


if (choice == 2) {

double celsius = reader.readDouble("Degrees Celsius: ");
double fahrenheit = ((9.0/5.0) * celsius) + 32;
System.out.println( celsius + " degrees Celsius = " + fahrenheit + " degrees Fahrenheit.");
}
}

}
 
Getting it to recognise "quit" at any point will complicate things... For a start, you'd need to read all your inputs as strings, and then convert them to integers or doubles.

A much simpler way of doing it would be to add a prompt at the end, like "Again? (y/n)".
Or better yet, add it as an option in your selection prompt:
Code:
1. Fahrenheit -> Celsius
2. Farhenheit <- Celsius
3. Quit
Then, as mentioned above, put the whole method in a while loop, and have the loop condition change to false if 3 is entered.
 
Back
Top