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.
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);
}
}
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);
}
double c, f; declares two double variables to store the temperature in Celsius (c) and Fahrenheit (f).System.out.print("Please enter temperature in celsius: "); prompts the user to enter a temperature in Celsius.c = s.nextDouble(); reads the double input and assigns it to the variable c.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.s.close(); closes the Scanner object to free up resources.System.out.print("Temperature in fahrenheit: " + f); prints the temperature in Fahrenheit.