How do I test for an exact value of a string from user input?

Hello, I'm writing a Temperature Converter program which asks for the unit from the user as a string.
My first two lines of code are as follows:
initialTemp = prompt('What is the Temperature? In Kelvin, Celsius, Fahrenheit, Or Rankine'); whatUnit = prompt('What Unit is it In?: Kelvin, Celsius, Fahrenheit, Or Rankine?: ');
What I am trying to figure out is how I would test to see if the whatUnit String input was equal too 'Kelvin', Celsius,Fahrenheit, Or Rankine. using an IfStatement.
For example, I want the program to compare the whatUnit String to 'Kelvin' or Celsius, and if the string doesn't exactly match Kelvin or Celsius, then I want to display an error message.
if whatUnit ~= 'Kelvin', error(msg); else if whatUnit == 'Kelvin' && 'Celsius" //convertTempCode Goes Here// end
in other words, if the whatUnit String entered is not equal to 'Kelvin', then I want to display an error message: error(msg). When I try to use this if statement, it gives me an error and tells me to strcmp function, but I find that doesn't solve my problem.

Answers (1)

strcmp(whatUnit, 'Kelvin')
If you have r2017a or newer you could use
whatUnit ~= "Kelvin"
Note that these are exact matches. It would be more forgiving to the user if you did a case insensitive match, and even more forgiving if you also permitted the standard unit abbreviations such as C and K and R

Categories

Asked:

on 8 Nov 2018

Answered:

on 8 Nov 2018

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!