Home > Blockchain >  Java checking if input is a double or character
Java checking if input is a double or character

Time:10-09

I'm writing a program in Java that does temperature conversion, but running into an issue.

import java.util.*;
public class TempCon2 {
    public static void main (String[] args) {
        double f,c,temp;
        char ch,op;
        Scanner sc = new Scanner(System.in);
        System.out.println("This program converts temperatures from Fahrenheit to Celsius and vica versa.");
        do {
            System.out.print("Please enter your temperature: ");
            temp = sc.nextDouble();
            System.out.print("Please enter the units (F/C): ");
            ch = sc.next().charAt(0);
            if(ch=='F') {
                    c=(temp-32)*5/9;
                    System.out.println("\nThe temperature of "   temp   " degrees Fahrenheit is equivalent to "   c   " degrees Celsius!"); }
            else if(ch=='C') {
                    f=(temp*9/5) 32;
                    System.out.println("\n The temperature of "   temp   " degrees Celsius is equivalent to "   f   " degrees Fahrenheit!"); }
            System.out.print("Do you wish to do another conversion? (Y/N): "); 
            op=sc.next().charAt(0);
            System.out.println();
            if(op=='N' || op=='n') {
                break; }
        }while((op=='Y' || op=='y'));
        System.out.println("Thank you, Goodbye");
    }
}

I want to be able to check when the user inputs their temperature if its a number, and if not it returns a message that says " 'user input' is not a number. Please enter a number". As well as when it asks for the units that if you enter anything other than "F" or "C" it does the same as the number one.

CodePudding user response:

You can try by parsing the String value to Double:

Double temp;
try {
    temp = Double.parseDouble(sc.nextLine());
} catch (NumberFormatException nfe){
    System.out.println("The input is not a number");
    break;
}

From Double.parseDouble doc:

NumberFormatException – if the string does not contain a parsable double.

CodePudding user response:

What you want is 'complex', in the sense that you don't hunt for a single method that does this; there is no scanner.askForCorFAndKeepAskingIfTheyEnterSomethingElse();.

So, you do the same thing you always do when faced with a task you want to do repeatedly which isn't trivial: You make a method.

public static char askTemperatureUnit(Scanner s) {
 ...
}

public static double askTemperatureAmount(Scanner s) {
 ...
}

These methods will use a few aspects:

  1. a while (true) loop. If the result is what you wanted, return it. (which also ends the loop by returning out of it). Otherwise, you tell the user they didn't enter what you wanted and let it loop.

  2. A way to respond when the user fails to enter a double value:

while (true) {
  try {
    return scanner.nextDouble();
  } catch (InputMismatchException e) {
    scanner.next(); // eat the invalid input away
    System.out.println("Hey now enter a number please!");
  }
}

You can also call scanner.next() and then use try/catch to run Double.parseDouble - same end result, whatever you feel is best.

While you're at it, c = Character.toUpperCase(c) lets you turn an n into an N which is nice.

CodePudding user response:

You need a couple of more do-while loops the way you have put for prompting the user if they want to continue.

I also recommend you use Scanner::nextLine to avoid the problems mentioned in this thread.

public class Main {
    public static void main(String[] args) {
        double f, c, temp;
        char ch, op;
        Scanner sc = new Scanner(System.in);
        System.out.println("This program converts temperatures from Fahrenheit to Celsius and vica versa.");
        do {
            boolean valid;
            do {
                valid = true;
                System.out.print("Please enter your temperature: ");
                try {
                    temp = Double.parseDouble(sc.nextLine());
                    do {
                        valid = true;
                        System.out.print("Please enter the units (F/C): ");
                        ch = sc.nextLine().charAt(0);
                        if (ch == 'F') {
                            c = (temp - 32) * 5 / 9;
                            System.out.println(
                                    "\nThe temperature of "   temp   " degrees Fahrenheit is equivalent to "   c
                                              " degrees Celsius!");
                        } else if (ch == 'C') {
                            f = (temp * 9 / 5)   32;
                            System.out
                                    .println("\n The temperature of "   temp   " degrees Celsius is equivalent to "   f
                                              " degrees Fahrenheit!");
                        } else {
                            System.out.println("Invalid input. Enter F or C");
                            valid = false;
                        }
                    } while (!valid);
                } catch (NumberFormatException e) {
                    System.out.println("Invalid input. Enter a number only");
                    valid = false;
                }
            } while (!valid);
            System.out.print("Do you wish to do another conversion? (Y/N): ");
            op = sc.nextLine().charAt(0);
            System.out.println();
            if (op == 'N' || op == 'n') {
                break;
            }
        } while ((op == 'Y' || op == 'y'));
        System.out.println("Thank you, Goodbye");
    }
}

A sample run:

This program converts temperatures from Fahrenheit to Celsius and vica versa.
Please enter your temperature: abc
Invalid input. Enter a number only
Please enter your temperature: 12.5
Please enter the units (F/C): X
Invalid input. Enter F or C
Please enter the units (F/C): F

The temperature of 12.5 degrees Fahrenheit is equivalent to -10.833333333333334 degrees Celsius!
Do you wish to do another conversion? (Y/N): y

Please enter your temperature: xyz
Invalid input. Enter a number only
Please enter your temperature: pqr
Invalid input. Enter a number only
Please enter your temperature: -40
Please enter the units (F/C): a  
Invalid input. Enter F or C
Please enter the units (F/C): F

The temperature of -40.0 degrees Fahrenheit is equivalent to -40.0 degrees Celsius!
Do you wish to do another conversion? (Y/N): n

Thank you, Goodbye
  •  Tags:  
  • java
  • Related