如何在prolog中控制用户输入?

时间:2014-12-03 14:04:31

标签: prolog

我的prolog中的代码存在这个问题。

它是关于时尚造型师专家系统,从用户获取属性并给她指定的外观。

以下是代码:

main_level(2):- 
    write('Please enter weight (60s (1), 50s (2)): '), read(W),
    write('Please enter tall (more than 160 (1), less than 160 (2)): '), read(T),
    write('Please enter skin color (bronze (1), white (2), black (3)): '), read(S1),
    write('Please enter hair length (medium (1), short (2), long (3)): '), read(H1),
    write('Please enter hair color (brown (1), black (2), blond (3)): '), read(H2),
    write('Please enter event (wedding (1), fami party (2): '), read(E),

但是我如何强迫用户输入正确的答案,所以在用户输入正确的答案之前程序将无法完成?

我尝试使用递归规则来做到这一点,但它也没有用!

2 个答案:

答案 0 :(得分:1)

基本上,您可以使用此架构验证每个输入:

main_level(2):- 
    repeat, write('Please enter weight (60s (1), 50s (2)): '), read(W), (W == 1 ; W == 2),
    repeat, write('Please enter tall (more than 160 (1), less than 160 (2)): '), read(T), (T == 1 ; T == 2),
...

但我建议改为编写一个简单的菜单,比如

menu(Header, Choices, Choice) :-
  repeat,
  write(Header),
  forall(nth1(I,Choices,Value), format('~w (~d) ', [Value,I])),
  read(C),
  nth1(C, Choices, _). % validate index input

并用

调用它
main_level(2):- 
    menu('Please enter weight ',['60s','50s'], W),
    menu('Please enter tall ',['more than 160','less than 160'], T),
    ...

答案 1 :(得分:1)

您可以测试答案是否等于预期值,如果规则失败,您可以在此检查后使用剪切(!)来显示错误消息,如下所示。

main_level(2):- 
write('Please enter weight (60s (1), 50s (2)): '), 
read(W), (W == 1; W == 2),!,...

main_level(2):- write('Please enter a value according to the menu').