Asking for user input in while loop

12 Ansichten (letzte 30 Tage)
Carlin Coleman
Carlin Coleman am 4 Apr. 2019
I am tasked with creating a while loop that after asking an initial question, ask the user "Do another? Y/Q" where if the user answers "Q" or "q", the loop will end and if the user answers "Y" or "y", the loop will continue. I am able to do this one time, but after entering a reply for "Do another? Y/Q", it says there is an undefined function of variable y as well as an error in "answer = input ("Another? "Y/Q"), and then proceeds to continue to ask me the "do another" input. I feel like I'm on the right track but maybe the logic is and order is wrong? Or I'm missing some key element? Help?
classnum = input("Enter ClassNum integer");
classname = "";
answer = "Y";
while (answer == "y" || answer == "Y")
answer = input("Another? Y/Q");
if (answer == "Q" || answer == "q")
break
end
classnum = input("Enter ClassNum integer");
if (classnum > 11 || classnum < 0)
fprintf("Error")
end
if (classnum == 0)
classname = "Barbarian";
end
if (classnum == 1)
classname = "Bard";
end
if (classnum == 2)
classname = "Cleric";
end
if (classnum == 3)
classname = "Druid";
end
if (classnum == 4)
classname = "Fighter";
end
if (classnum == 5)
classname = "Monk";
end
if (classnum == 6)
classname = "Paladin";
end
if (classnum == 7)
classname = "Ranger";
end
if (classnum == 8)
classname = "Rogue";
end
if (classnum == 9)
classname = "Sorcerer";
end
if (classnum == 10)
classname = "Wizard";
end
if (classnum == 11)
classname = "Aberration";
end
end
fprintf(classname);

Antworten (1)

José María García Morillo
José María García Morillo am 20 Mär. 2022
Actually, when using the syntax
answer = input("Another? Y/Q");
you are telling MATLAB that the expected answer is a numeric expression to evaluate. As you are returning either "y" or "q", MATLAB tries to evaluate that expression by looking for variables with such names in the workspace, thus failing and showing up that error message you got (exactly as it would happen if you just entered "y" or "q" in the command window).
It turns out that you are lacking a second argument that lets MATLAB know that answer is in fact a string (see MATLAB input documentation). Your code should then be:
answer = input("Another? Y/Q",'s');

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by