Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

While loop help.

Hi guys!

How would you recommend changing this to make it not output "999 Celsius is equal to 1830 Fahrenheit" as it exits?

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class Main {
    private static int mVarC;

    public static void main(String[] args) {
        do {
            try {
                System.out.println("Please enter a Celsius Value - Enter 999 to quit");
                promptForC();
                convertToF(mVarC);
            } catch(IOException ioe) {
                System.out.println("Oops, That input is not valid");
            }
        } while(mVarC != 999);

    }

    // Prompts User for Input
    private static void promptForC() throws IOException {
        BufferedReader buffer=new BufferedReader(new InputStreamReader(System.in));
        mVarC = Integer.parseInt(buffer.readLine());
    }

    // Converts Celcius to Fahrenheit
    private static int convertToF(int arg){
        double VarF = (arg * 1.8) + 32;
        System.out.println(String.format("%d Celsius is equal to %d Fahrenheit\n",mVarC, (int) Math.round(VarF)));
        return (int) Math.round(VarF);
    }
}

I fixed it with an if statement in main().

Now to work on handling exceptions from non-integer inputs....

1 Answer

do {
            try {
                System.out.println("Please enter a Celsius Value - Enter 999 to quit");
                promptForC();
                if (mVarC == 999) {
                    System.out.println("Thanks!Exit.");
                    System.exit(0);
                }
                convertToF(mVarC);
            } catch(IOException ioe) {
                System.out.println("Oops, That input is not valid");
            }
        } while(mVarC != 999);