1

I need some code that will tell whether or not some user input is a double. If it is a double, I need it stored in the variable degreeCelsius and if it isn't, I need the program to exit. Overall, the program is going to take some double values and use them as degrees Celsius and convert them to degrees Fahrenheit. This is what I have so far:

import java.util.*;
public class Lab4b
{
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        double degreeCelsius = 0.0;
        double degreeFahrenheit = 0.0;
        System.out.println("Celcius    | Fahrenheit");

        while(scan.next() != null)
            {    
//this is where I need the code. If you see any other errors, feel free to correct me
            //if (degreeCelsius = Double)
                    {
                        degreeCelsius = scan.nextDouble();
                    }
                else
                    {
                        System.exit(0);
                    }
                degreeFahrenheit = degreeCelsius * (9.0/5.0) + 32.0;
            }
    }
}
0xCursor
  • 2,224
  • 4
  • 13
  • 30
gdhc21
  • 87
  • 5
  • 16
  • 2
    Formatting aside, there's a few things wrong here. `scan.next() != null` is not a proper way to ensure that there are elements left in the scanner, and you do nothing with `degreeFahrenheit` after you calculate it. My gut feeling tells me you need two separate methods for this. – Makoto Sep 18 '13 at 03:19
  • We haven't been taught how to create multiple methods, it's for an intro to java class. I'm a beginner at this and would appreciate any help. Could I upload the instructions? – gdhc21 Sep 18 '13 at 03:22
  • No, creating a Celsius/Fahrenheit converter is straightforward enough. If you can't use two separate methods, then consider addressing the issue of not doing anything with `degreeFahrenheit` after it's calculated. – Makoto Sep 18 '13 at 03:23
  • Don't understand you mean , if in `scan.nextDouble()` returns a String for example? it will throw an `InputMismatchException` if can't convert. – nachokk Sep 18 '13 at 03:56

6 Answers6

1

Since you may not get a double entered, best to read in a String, then attempt to convert it to a double. The standard pattern is:

Scanner sc = new Scanner(System.in);
double userInput = 0;
while (true) {
    System.out.println("Type a double-type number:");
    try {
        userInput = Double.parseDouble(sc.next());
        break; // will only get to here if input was a double
    } catch (NumberFormatException ignore) {
        System.out.println("Invalid input");
    }
}

The loop can't exit until a double has been entered, after which userInput will hold that value.

Note also how by putting the prompt inside the loop, you can avoid code duplication on invalid input.

Bohemian
  • 365,064
  • 84
  • 522
  • 658
0

Here's one way to modify your while:

    while(scan.hasNextDouble()) {
        degreeCelsius = scan.nextDouble();
        degreeFahrenheit = degreeCelsius * (9.0/5.0) + 32.0;
        System.out.println(degreeCelsius + " in Celsius is " + degreeFahrenheit + " in Fahrenheit");

    }

Keep in mind that event with Scanner breaking up input by whitespace, you still usually need to press enter between entries due to Unix and Windows default terminal settings.

So here for more info:

How to read a single char from the console in Java (as the user types it)?

Community
  • 1
  • 1
masahji
  • 534
  • 2
  • 6
0

Use Double.parse method. See doc here.

Using the above method, parse the user input and catch the NumberFormatException. Any user input that is not Double-parseable willthrow the exception inside which you can break the loop.

Kumar Sambhav
  • 6,675
  • 13
  • 56
  • 82
0

try this

while (scan.hasNext()) {
   if (scan.hasNextDouble()) {
      double d = scan.nextDouble();
      ...
   } else {
      ...
Evgeniy Dorofeev
  • 124,221
  • 27
  • 187
  • 258
0

You can use the below method to check if your input string is double or not.

public boolean isDouble(String inputString) {
    try {
            Double d=Double.parseDouble(inputString);
        return true;
    } catch (NumberFormatException e) {
        return false;
    }
}
MansoorShaikh
  • 897
  • 5
  • 18
0
import java.util.Scanner;

public class TempConversion
{
    public static void main(String []args)
    {
        Scanner scan = new Scanner(System.in);
        String degSymbol = "\u00b0"; // unicode for the 'degree' symbol 

        do {
            try {
                System.out.print("\nEnter temperature or press q to exit: ");
                String input = scan.next();
                if (input.equals("q") || input.equals(" ")) {
                    System.exit(0);
                } else {
                    double temp_input = Double.parseDouble(input);

                    System.out.printf("What unit of temp is %,.2f? " +
                                      "\nCelsius\nFarenheit\nKelvin: ", temp_input);
                    char unit_from = scan.next().toUpperCase().charAt(0);

                    System.out.printf("\nConvert %,.2f%s%c to what unit? " +
                                      "\nCelsius\nFarenheit\nKelvin: ", 
                                      temp_input, degSymbol, unit_from);
                    char unit_to = scan.next().toUpperCase().charAt(0);

                    String convert = Character.toString(unit_from) +
                                     Character.toString(unit_to);

                    switch(convert) {
                    case "CF": //celsius to farenheit
                        double temp_results = (9.0/5.0) * temp_input + 32;
                        System.out.printf("\nRESULT: %,.2f\u00b0%c = %,.2f\u00b0F\n", 
                                          temp_input, unit_from, temp_results);   
                        break;
                    case "FC": // farenheit to celsius
                        temp_results = (5.0/9.0) * (temp_input - 32);
                        System.out.printf("\nRESULT: %,.2f\u00b0%c =     %,.2f\u00b0C\n",
                                          temp_input, unit_from, temp_results);
                        break;
                    case "CK": //celsius to kelvin
                        temp_results = temp_input + 273.15;
                        System.out.printf("\nRESULT: %,.2f%s%c = %,.2f%sK\n", temp_input,
                                          degSymbol, unit_from, temp_results, degSymbol);
                        break;
                    case "FK": // farenheit to kelvin
                        temp_results = (temp_input + 459.67) * 5.0/9.0;
                        System.out.printf("\nRESULT: %,.2f%s%c = %,.2f%sK\n", temp_input,
                                          degSymbol, unit_from, temp_results, degSymbol);
                        break;
                    case "KF": // kelvin to farenheit
                        temp_results = temp_input * 9.0/5.0 - 459.67;;
                        System.out.printf("\nRESULT: %,.2f%s%c = %,.2f%sF\n", temp_input,
                                          degSymbol, unit_from, temp_results, degSymbol);
                        break;
                    case "KC": // kelvin to celsius
                        temp_results = temp_input - 273.15;
                        System.out.printf("\nRESULT: %,.2f%s%c = %,.2f%sC\n", temp_input,
                                          degSymbol, unit_from, temp_results, degSymbol);
                        break;
                    default:
                        System.out.println("\nERROR: One or more variables you entered " +
                                           "are invalid. Please try again.");
                        break;
                    } // ends switch
                } // ends else
            } catch (NumberFormatException ignore) {
                System.out.println("Invalid input.");
            }
        } while(true); //ends do
    } // ends main
} // ends class