# How do I get my MATLAB code to display an error if the user input number is less than four digits and has less than two distinct numbers?

2 visualizaciones (últimos 30 días)
Richard el 26 de Feb. de 2024
Editada: Walter Roberson el 26 de Feb. de 2024
clear
clc
constant = 6174; % Initialize end condition of while loop
steps = 0; % Initialize steps in a loop
user = input('Please enter a 4 digit number: ') % User inputs a number
digits = num2str(user);
if numel(num2str(user)) < 4 && length(unique(digits)) < 2{
disp("Error. Not a valid number. Enter a four digit number with at least two distinct numbers")
}
end
##### 0 comentariosMostrar -2 comentarios más antiguosOcultar -2 comentarios más antiguos

Iniciar sesión para comentar.

Walter Roberson el 26 de Feb. de 2024
user = input('Please enter a 4 digit number: ') % User inputs a number
digits = num2str(user);
if numel(digits) < 4 || length(unique(digits)) < 2
error("Error. Not a valid number. Enter a four digit number with at least two distinct numbers");
end
However, you have problems if the user inputs a number starting with 0.
##### 2 comentariosMostrar NingunoOcultar Ninguno
Richard el 26 de Feb. de 2024
Thank you!
Is there a way to do it with a number with leading zeros?
Walter Roberson el 26 de Feb. de 2024
Editada: Walter Roberson el 26 de Feb. de 2024
digits = input('Please enter a 4 digit number: ', 's'); % User inputs a number
if numel(digits) ~= 4 || length(unique(digits)) < 2 || ~all(isstrprop(digits, 'digit'))
error("Error. Not a valid number. Enter a four digit number with at least two distinct numbers");
end

Iniciar sesión para comentar.

### Categorías

Más información sobre Physics en Help Center y File Exchange.

### Community Treasure Hunt

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

Start Hunting!

Translated by