Solved

Celsius conversion program

Posted on 2004-09-08
9
9,509 Views
Last Modified: 2010-07-27
I am very new to Java and am having a really hard time writing programs. I am trying to write a program that converts celsius to fahrenheit. The program should ask a user to input a temperature and either f for fahrenheit or c for celsius. It should not be case sensitive. I am ALL messed up. Here is what I have, but i cannot for the life of me figure out how the numeric portion and the character portion of the users input will be calculated seperately. Any hints would be greatly appreciated.

public class Degrees
{
    public static void main(String[] args)

    {

              /**List of tasks
              Ask for input
              Make sure type of degree is non-case sensitive
              Perform converstion and output
              Ask user to end program or perform another conversion
              */


            //double number;

            System.out.println("This program will convert degrees Celcius to Fahrenheit or vice versa"); //outputs sentence

          do
          {
                System.out.println("\nPlease enter a temperature and either a C for Celcius or F for Fahrenheit");
                char input = SavitchIn.readLineNonwhiteChar();
                System.out.println();
                //switch(input);
                //int degree = input.indexOf('f') && ('c');
                //number = (input.substring(0, degree));
                //degree = line.substring(char);

            double degreesC;
            double degreesF;

            degreesC = ((degreesF - 32) * 5)/9; //Fahrenheit to Celsius formula
                degreesF = ((9 * degreesC)/5) + 32; //Celsius to Fahrenheit formula


                System.out.println("Enter Q to quit or press any other key to perform another conversion");
                char quitAnswer = SavitchInReadLineChar(); //reads user input
                if(quitAnswer == 'q') //if user input is lowercase q
                         System.exit(0); //then exit the system
                else if(quitAnswer == 'Q') //if user input is uppercase Q
                         System.exit(0); //then exit the system

            }while (quitAnswer != 'q' && quitAnswer != 'Q'); //if it is neither, then start over
      }

}
0
Comment
Question by:nikese
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
9 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 12010690
>>char input = SavitchIn.readLineNonwhiteChar();

Don't know that Savitch class, but guess that should be

String input = SavitchIn.readLineNonwhiteChar();
0
 

Author Comment

by:nikese
ID: 12010737
How to the calculations work from there? I think it should be something like if input includes f then perform degreesC calculation else if it includes c then perform degreesF calculation. That's what I am thinking but i don't know how to write it in java. Also, it needs to be non-case sensitive but when I type out input = input.equalsIgnoreCase(); I get compiler errors.
0
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 200 total points
ID: 12010812
I'd do something like:

boolean exit = false;
do {
      System.out.println("\nPlease enter a temperature and either a C for Celcius or F for Fahrenheit");
      String input = SavitchIn.readLineNonwhiteChar();
      String[] atoms = input.split("\\s+");
      atoms[0] = atoms[0].trim();
      double temp = 0;
      switch (atoms[1].trim().charAt(0)) {
            case 'c':
                  // do C2F
                  temp = ((9 * Double.parseDouble(atoms[0])/5) + 32;
                  break;
            case 'f':
                  temp = ((Double.parseDouble(atoms[0]) - 32) * 5)/9; //Fahrenheit to Celsius formula
                  break;
            default:
                  exit = true;
      }
      System.out.println(temp);
}while(exit == false);
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Assisted Solution

by:sunnyjassal
sunnyjassal earned 100 total points
ID: 12010879
This code is from top of my head so check for syntax and logical errors. hope this helps.

I would just do the following:

char[] stringInCharForm = args.toCharArray();
String numString = new String("");
String letterString = new String("");
boolean foundPeriod = false;
for (int i=0; i < stringInCharForm.length; i++){
    char c = stringInCharForm[i];
    //over here check if character if it is from 0 to 9
    if (c == '.' && !foundPeriod){
       foundPeriod == true;
       numString = numString + c;
    }
    if (checkIfCharisNumber(c))
        numString = numString + c;
    else
        letterString = letterString + c;
   
}

float degrees = 0;
if (numString.equals("") || numString.equals(".")){
     throw new Exception ("You need to enter a number");
}
else
   degrees =  Float.parseFloat(numString);


That should do it. All other characters are found in letterString this is assuming that user types in 86 F or 36 C or F 12 or 88.0 Celsius, bascially as long as numbers are together and letter part is together.
otherwise if 86Cel.22ci.us11 is typed number part is going to be 88.2211 and String part is going to be Celcius

The simplest way to write checkIfCharisNumber() would be
public boolean checkIfCharisNumber(char c){
       boolean found = false;
       for (int i =0; i < 10; i++){
           if (c == i)
           {
                 found = true;
                 break;
            }
        }
       return found;
}
0
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 200 total points
ID: 12010932
This will run - just make sure your SavitchIn is visible:


class C2F {

  public static void main(String[] args) {
      boolean exit = false;
      do {
          System.out.println("\nPlease enter a temperature and either a C for Celcius or F for Fahrenheit");
          String input = SavitchIn.readLineNonwhiteChar();
          String[] atoms = input.split("\\s+");
          atoms[0] = atoms[0].trim();
          double temp = 0;
          char x = atoms.length > 1? atoms[1].trim().charAt(0) : atoms[0].charAt(0);
          switch (x) {
               case 'c':
                    // do C2F
                    temp = (9 * Double.parseDouble(atoms[0])/5) + 32;
                     break;
               case 'f':
                    temp = ((Double.parseDouble(atoms[0]) - 32) * 5)/9; //Fahrenheit to Celsius formula
                    break;
               default:
                    exit = true;
          }
          if (!exit) {
            System.out.println(temp);
          }
      }while(exit == false);

  }


}
0
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 200 total points
ID: 12010951
Small adjustment. Change

>>switch (x) {

to

switch (Character.toLowerCase(x)) {
0
 
LVL 1

Accepted Solution

by:
lmahmud earned 200 total points
ID: 12011105
I think this will work with your SavitchIn class

public class Degrees
{      
      
      public static char quitAnswer;
      public static double degreesC;
    public static double degreesF;
      
    public static void main(String[] args)

    {

             /**List of tasks
             Ask for input
             Make sure type of degree is non-case sensitive
             Perform converstion and output
             Ask user to end program or perform another conversion
             */


          //double number;

          System.out.println("This program will convert degrees Celcius to Fahrenheit or vice versa"); //outputs sentence

         do
         {
              System.out.println("\nPlease enter a temperature and either a C for Celcius or F for Fahrenheit");
              String inputString = SavitchIn.readLine();
              String number= inputString.substring(0, inputString.length() - 1);
              System.out.println("Number is " + number);
              String degree = inputString.substring(inputString.length() -1);
              System.out.println("degree is " + degree);
             
              int degreeNum = new Integer(number).parseInt(number);
              System.out.println("degree " + number + degree);

             
              if(degree.equalsIgnoreCase("f"))
                    System.out.println(((degreeNum - 32) * 5)/9);
              if(degree.equalsIgnoreCase("c"))
                System.out.println(((9 * degreeNum)/5) + 32);      
                    
                           

              System.out.println("Enter Q to quit or press any other key to perform another conversion");
              quitAnswer = SavitchIn.readChar(); //reads user input
              if(quitAnswer == 'q') //if user input is lowercase q
                      System.exit(0); //then exit the system
              else if(quitAnswer == 'Q') //if user input is uppercase Q
                      System.exit(0); //then exit the system

          }while (quitAnswer != 'q' && quitAnswer != 'Q'); //if it is neither, then start over
     }

}
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12011614
:-)
0
 

Author Comment

by:nikese
ID: 12012048
I wanted to thank you all tremendously!!!! I have worked on this program for four days now and it almost makes me laugh how easy it seemed to you. Thank you very much for your super fast replies. I think what I am going to do is run all of them to see the outcomes and take a little advice from each. Thanks again!
0

Featured Post

Enroll in May's Course of the Month

May’s Course of the Month is now available! Experts Exchange’s Premium Members and Team Accounts have access to a complimentary course each month as part of their membership—an extra way to increase training and boost professional development.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Is there a simpler dropbox system? 10 53
swing controls 2 37
Eclipse for Java EE development 2 68
Find out all repos that a user is most active on Github 1 57
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:

732 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question