1
\$\begingroup\$

Can anyone suggest any improvements? I already applied here the suggestions that was made for my first program (Guess the Number) that I posted.

import java.util.Scanner;

public class Temp { // convertion of fahrenheit to celcius and vise versa

    public static void main(String[] args) {
        double celcius, fahrenheit;
        Scanner in = new Scanner(System.in);

        System.out.print("Enter the value of temperature in degree celcius: ");
        celcius = in.nextDouble();
        fahrenheit = celcius * 9 / 5 + 32; // convertion formula for celcius to fahrenheit
        System.out.printf(celcius+" °C = %.1f °F\n", fahrenheit);

        System.out.print("Now enter the value of temperature in degree fahrenheit: ");
        fahrenheit = in.nextDouble();
        celcius = (fahrenheit - 32) * 5 / 9; // formula of fahrenheit to celcius
        System.out.printf(fahrenheit +" °F = %.1f °C\n", celcius);
    }
}
\$\endgroup\$
2
\$\begingroup\$

Here are some things I see that can improve your code.

Resource Management

To avoid resource leaks, it is usually good to close IO classes like java.util.Scanner if you won't be using them anymore. This is because the garbage collector only manages memory and not other resources.

in.close();

Modularity

Currently your program contains a main method that does all tasks. This is not a good idea if you choose to reuse some parts of it (E.G. doing celcius conversions multiple times). I think it is a good idea to put the two conversions into separate methods. That way the components of your program would be more reusable (specially if you choose to add more operations later) and would be more readable as a whole.

Error handling

At least write an error handling mechanism, even a general one. For example:

try (Scanner in = new Scanner(System.in)){
    // handle user inputs and conversions
} catch(IOException e) {
   // handle IO exception
}

Notice that I use Try with resources so the scanner resource rapped in the try block would automatically be closed after the block finishes executing. So no need to call in.close() anymore

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.