Skip to content

Instantly share code, notes, and snippets.

@QuanSai
Created October 31, 2012 05:17
Show Gist options
  • Save QuanSai/3984963 to your computer and use it in GitHub Desktop.
Save QuanSai/3984963 to your computer and use it in GitHub Desktop.
Temp conversion again; This time, just asking for the temp
import java.util.*;
public class Convert
{
public static void main(String[] args)
{
Float f, c; //f and c represent the actual float value of the input temperature
Scanner inTemp = new Scanner(System.in); //holds input Scanner object
char type; //holds the type of input temperature F or C
System.out.println("Temperature?");
/* Take user input. */
String fullTemp = inTemp.nextLine().toUpperCase(), //inTemp is the input temperature string; setting to uppercase makes parsing easier than opting not to
tempNumber, // tempNumber will hold just the number part of the input string
temp; //temp will hold the actual temperature number used for converting
/* Sanitize the input string for conversion. */
tempNumber = fullTemp.substring(0, fullTemp.length()-1); // tempNumber is just a substring; it is the numbers (only) before F or C
temp = tempNumber.replaceAll("[^0-9a-zA-Z._]+", ""); // remove everything that isn't a number, decimal, underscore, or space
/* Set the type of temperature entered. */
type = fullTemp.charAt(fullTemp.length()-1); // the last character is assumed to be 'F' or 'C' which is the type of temperature entered
if(type == 'F') //if the temp entered is Fahrenheit
{
System.out.println("That's a Fahrenheit temperature.");
try //try to compute the appropriate conversion
{
f = new Float(temp);
c = (f - 32.0f)*5.0f/9.0f;
System.out.printf("That's %.2f Celsius.\n", c);
}
catch(NumberFormatException e) // if there's a problem, it's likely a one that has to do with bad input
{
System.out.println("!Error: Could not yield Celsius temperature.");
System.out.println(e.getMessage());
}
}
else if(type == 'C') // if it's Celsius
{
System.out.println("That's a Celsius temperature.");
try
{
c = new Float(temp);
f = (c * 9.0f)/5.0f + 32;
System.out.printf("That's %.2f Fahrenheit.\n", f);
}
catch(NumberFormatException e)
{
System.out.println("!Error: Could not yield Fahrenheit temperature.");
System.out.println(e.getMessage());
}
}
else //Otherwise, a proper temperature wasn't designated
{
System.out.println("!Error: Couldn't resolve the temperature type.");
System.out.println("!Error: Please put 'F' or 'C' at the end of a number.");
}
}//end main()
}//end class Convert
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment