我正在研究课程选择脚本,每个人只能选择三个课程。我遇到的问题是,如果用户选择的课程少于或多于三个,则如何重复从列表中进行选择,并且只有在选择了三个选择时才继续进行。将列表中的选项转换为字符串应该可以,但是从列表中选择后什么也没发生
set theClassList to {"Math ", "English ", "Science ", "I&S ", "Design "}
repeat
set theClass to choose from list theClassList with prompt "Select three courses" with multiple selections allowed
set theClassString to theClass as string
if words in theClassString ≠ 3 then
display dialog "Please select three courses"
exit repeat
else if words in theClassString = 3 then
display dialog "Ok"
end if
end repeat
答案 0 :(得分:0)
对theClassString
中的单词进行计数是一个聪明的主意(可以使用number of words in theClassString
而不是简单地words in theClassString
来完成)。在大多数情况下,这将一直有效,直到用户将"I&S"
作为他们的选项之一为止,可悲的是,由于与号不是一个单词,因此将其"I"
和"S"
视为两个单词字符。
您还把exit repeat
放在了if...then...else
块的错误一半,因为您想在用户选择3门课程时打破循环,而不是在他们没有选择3门课程时就打破循环。
您应该只计算结果中的项目数,而不是尝试将列表选择的结果强制转换为字符串,这可以通过以下三种方式之一进行:
count theClass
length of theClass
number in theClass
这是脚本的重做版本:
property theClassList : {"Math ", "English ", "Science ", "I&S ", "Design "}
property text item delimiters : linefeed
set choices to missing value
repeat
if choices ≠ missing value then display dialog ¬
"You must select precisely three courses"
set choices to choose from list theClassList with prompt ¬
"Select three courses" with multiple selections allowed
if choices = false or the number of choices = 3 then exit repeat
end repeat
if choices = false then return
display dialog choices as text
...这是一个使用递归处理程序而不是重复循环的版本:
property theClassList : {"Math", "English", "Science", "I&S", "Design"}
property text item delimiters : linefeed
to choose()
tell (choose from list theClassList ¬
with prompt ("Select three courses") ¬
with multiple selections allowed) to ¬
if it = false or its length = 3 then ¬
return it
display dialog "You must select precisely three courses"
choose()
end choose
display alert (choose() as text)
答案 1 :(得分:0)
通过尊重脚本的流畅性使其变得更容易。最好将您的“ theClass”声明为相当字符串的列表,然后将n声明为list的计数。以下是经过修改的脚本或以下脚本,它们带有您自己的脚本,但声明n为“ theClassString”中的单词计数。
set theClassList to {"Math", "English", "Science", "I & S", "Design"}
repeat
set theClass to choose from list theClassList with prompt "Select three courses" with multiple selections allowed
set theClassString to theClass as list
set n to count of theClassString
set n to do shell script "echo" & n
if n ≠ "3" then
display dialog "Please select three courses"
exit repeat
else if n = "3" then
display dialog "Ok"
end if
end repeat
下方 通过声明String
set theClassList to {"Math ", "English ", "Science ", "I&S ", "Design "}
repeat
set theClass to choose from list theClassList with prompt "Select three courses" with multiple selections allowed
set theClassString to theClass as string
set n to count of words in theClassString
set n to do shell script "echo " & n
if n ≠ "3" then
display dialog "Please select three courses"
exit repeat
else if n = "3" then
display dialog "Ok"
end if
end repeat