Applescript с использованием операторов if then и выбора - PullRequest
0 голосов
/ 04 января 2019

Я работаю над сценарием выбора курса, и каждый может выбрать только три курса.У меня возникают проблемы с выяснением того, как повторить выбор из списка, если пользователь выбирает менее или более трех курсов, и продолжит работу, только если выбраны три варианта.Преобразование вариантов из списка в строку должно работать, однако после выбора из списка ничего не происходит

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

Ответы [ 2 ]

0 голосов
/ 05 января 2019

, чтобы облегчить задачу, соблюдая текучесть вашего сценария.Было бы лучше объявить ваш "theClass" как довольно строковый список и объявить n как счетчик списка.Ниже приведен ваш измененный сценарий или следующий, который принимает ваш собственный, но объявляет 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

Ниже, объявив строку

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
0 голосов
/ 04 января 2019

Это умная идея, чтобы посчитать слова в theClassString (что было бы сделано с использованием number of words in theClassString вместо простого words in theClassString).Это будет работать большую часть времени, пока пользователь не включит "I&S" в качестве одной из своих опций, что, к сожалению, считается двумя словами, "I" и "S", поскольку амперсанд не является символом слова.

Вы также указали exit repeat в неправильной половине блока if...then...else, поскольку вы хотите разорвать цикл, когда пользователь выбирает 3 курса, а не когда он не выбирает 3 курса.

Скореечем пытаться привести результат выбора списка в строку, вам нужно просто посчитать количество элементов в результате, что можно сделать одним из трех способов:

  1. count theClass
  2. length of theClass
  3. 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)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...