Asking for user input in while loop

조회 수: 11 (최근 30일)
Carlin Coleman
Carlin Coleman 2019년 4월 4일
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);

답변 (1개)

José María García Morillo
José María García Morillo 2022년 3월 20일
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');

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by