Data types and variables
Operators
Modules and Packages
Conversion Programs
More Code Examples
Cheat Sheet

Python Code Example: Convert Celsius to Fahrenheit

This code example demonstrates how to convert a temperature from Celsius to Fahrenheit. The program prompts the user to enter a temperature in Celsius, performs the conversion using the formula F=C×1.8+32, and then prints the temperature in Fahrenheit.
This example highlights the use of basic arithmetic operations, user input handling, and output formatting in Java.

Code Example

import java.util.Scanner;

public class ConvertCelsiusToFahrenheit {
    public static void main(String[] args) {
        double c, f;

        Scanner s = new Scanner(System.in);
        System.out.print("Please enter temperature in celsius: ");

        c = s.nextDouble();
        f = c * 1.8 + 32;

        s.close();

        System.out.print("Temperature in fahrenheit: " + f);
    }
}

Code Explanation

Main Method

public static void main(String[] args)

The main method executes the program and contains the logic for converting the temperature from Celsius to Fahrenheit.

public static void main(String[] args) {
    double c, f;

    Scanner s = new Scanner(System.in);
    System.out.print("Please enter temperature in celsius: ");

    c = s.nextDouble();
    f = c * 1.8 + 32;

    s.close();

    System.out.print("Temperature in fahrenheit: " + f);
}

Variable Declaration

  • double c, f; declares two double variables to store the temperature in Celsius (c) and Fahrenheit (f).

Prompting for User Input

  • System.out.print("Please enter temperature in celsius: "); prompts the user to enter a temperature in Celsius.

Reading User Input

  • c = s.nextDouble(); reads the double input and assigns it to the variable c.

Converting Celsius to Fahrenheit

  • f = c * 1.8 + 32; performs the conversion using the formula F=C×1.8+32F = C \times 1.8 + 32F=C×1.8+32 and assigns the result to the variable f.

Closing the Scanner

  • s.close(); closes the Scanner object to free up resources.

Printing the Result

  • System.out.print("Temperature in fahrenheit: " + f); prints the temperature in Fahrenheit.