How can I get a user to input a number which is not already

1 visualizzazione (ultimi 30 giorni)
Hi, I just want a user to input(input must be between 1-9) a new number, so store the input value in a vector and add every new input to that vector and every time the user input new number I just use a code to check is the input is already in the vector, but my code is not check every value in the vector.
o=[];
for i=1:4
num=input('Enter:');
while num<=0||num>=9
num=input('Enter exist number:');
end
for i=1:length(o)
if num==o(i)
while num==o(i)
num=input('Enter new:');
end
end
end
o=[o num];
end
This is my code, can anyone please help
Thanks,

Risposta accettata

Rik
Rik il 22 Apr 2023
What you need to do, is to put your input statement at the start of the while loop, and then you can use ismember instead of a loop to check for matches.
Note that you should ask the user for the number in a char vector, and then use str2double to convert the char to a number.
The bottom line is that you should split the tasks of asking the user for a number and validating that input. You should write it in such a way that you can put those things in separate functions.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Prodotti


Release

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by