Programming Fundamentals/Conditions/Java: Difference between revisions

From Wikiversity
Jump to navigation Jump to search
Content deleted Content added
Creating
(No difference)

Revision as of 02:15, 3 February 2017

conditions.java

import java.util.*;

class conditions
{
    private static Scanner input = new Scanner(System.in);
    
    public static void main(String[] args)
    {
        String choice;
        
        System.out.println("Enter F to convert to Fahrenheit or C to convert to Celsius:");
        choice = input.nextLine();
        if (choice.equals("C") || choice.equals("c"))
        {
            toCelsius();
        }
        else if (choice.equals("F") || choice.equals("f"))
        {
            toFahrenheit();
        }
        else
        {
            System.out.println("You must enter C to convert to Celsius or F to convert to Fahrenheit!");
        }
    }

    private static void toCelsius()
    {
        double f;
        double c;
        
        System.out.println("Enter Fahrenheit temperature:");
        f = input.nextDouble();
        c = (f - 32) * 5 / 9;
        System.out.println(f + "° Fahrenheit is " + c + "° Celsius");
    }

    private static void toFahrenheit()
    {
        double c;
        double f;
        
        System.out.println("Enter Celsius temperature:");
        c = input.nextDouble();
        f = c * 9 / 5 + 32;
        System.out.println(c + "° Celsius is " + f + "° Fahrenheit");
    }
}

Try It

Copy and paste the code above into one of the following free online development environments or use your own Java compiler / interpreter / IDE.

See Also