好的,所以不确定apple.stackexchange是否是一个更好的地方,但我需要一些这方面的帮助:
目标:要求用户输入应重复循环的次数。如果他们以错误的格式输入反馈,请发送反馈
问题如果我输入小数,它只是将其作为整数并且仍然有效,我该如何防止这种情况,或者以另一种方式检查?
set correctEntry to false --initially assume false
repeat while correctEntry is false
--Let user put how many times it loops
set textToDisplay to "How often should this repeat?"
display dialog textToDisplay default answer "2.4"
set reps to text returned of the result
--Detailed check/feedback if they input wrong
try
--Begins as string, try making it an integer
set reps to reps as integer --coercion will should only work with integer
set correctEntry to true --remember won't get here if first statement fails
on error
try
--See if string can at least be converted to a number
set reps to reps as number
display dialog "Only integers"
on error
display dialog "That wasn't a number"
end try
-- still false here
end try
end repeat
--Only gets here if correctEntry becomes true
repeat reps times
say "You entered right"
end repeat
另外,要检查是否输入了负数,我只会使用
if reps > 0
set reps to reps as integer
set correctEntry to true
else
display dialog "Must be positive"
有更好的方法吗?即使是内置的“积极”电话?
最后,我使用http://www.fischer-bayern.de/as/as4as/AS4AS_e.pdf作为教程,但我不确定它是否足够好。我当时正考虑去Mac OS X Developer Library,但是想要一些好的学习方法。我只有一点Perl经验,所以它不一定是一个完整的初学者。
更新:找到此网站:http://www.macosxautomation.com/training/applescript/intro.html
非常感谢您提供的任何帮助。
Update2:如果我对第二个try块中的整数使用相同的检查,则代码有效,第一个块有什么问题。为什么它将所有内容都算作整数?更重要的是,为什么使用if语句建议如果放在我的脚本中不起作用?
答案 0 :(得分:4)
试试这个......
repeat
set textToDisplay to "How often should this repeat?"
set reps to text returned of (display dialog textToDisplay default answer "2.4")
try
set reps to reps as number -- this makes sure no letters were entered
if (class of reps) is integer and reps is greater than 0 then
exit repeat
else
error "Only positive integers"
end if
on error theError number errorNumber
display dialog "There was an error: " & (errorNumber as text) & return & return & theError buttons {"OK"} default button 1 with icon stop
end try
end repeat
repeat reps times
say "You entered right"
end repeat
学习here's some tutorials。当我了解到我在“初学者脚本教程”部分中做了那些。随着你变得更好,还有更高级的教程。最后,您还必须学习AppleScript编辑器中“帮助”菜单下的“Applescript语言指南”。