2012-03-27 64 views
1

我對我的UNIX編號猜測遊戲存在邏輯問題。菜單系統工作得很好(1玩,2退出,否則防守反應)。但是,一旦在比賽中我得到的輸出如下:UNIX編號猜測遊戲 - 邏輯問題

  1. 選項:
  2. (1.播放)
  3. (2號出口)
  4. 輸入數字1或2
  5. 請輸入你猜到的。
  6. pgm01 [43]:[5:沒有發現[沒有這樣的文件或目錄]
  7. pgm01 [47]:[5:沒有發現[沒有這樣的文件或目錄]
  8. 耶!! ! 5是正確的數字!
  9. 你嘗試的總數爲0。

下面是代碼(FYI這是在KSH殼)。我猜我有某種語法錯誤的地方...

#!/bin/ksh 
    # CS2351 - UNIX Programming 
    # Program 1 

    x=$RANDOM%100+1 
    tries=0 
    guessInt=0 
    userOption=0 

    while ((1==1)) 
    do 
    print "Welcome to the UNIX Number Guessing Game!" 
    print "A random number between 1 and 20 has been selected." 
    print "===========\nDirections: \n===========" 
    print "1. Enter your guess. The program will tell you if it is high or low." 
    print "2. The program will tell you if it is high or low." 
    print "3. Change your guess." 
    print "4. The computer will tell you how many guesses you had." 
    print "=======\nOPTIONS\n=======" 
    print "1: Play \n2: Exit" 
    print "Enter number 1 or 2." 

    "Enter number 1 or 2." 

    read userinput 
    case "$userinput" in 

    1) 
     break;; 
    2) 
     print "Quitting program!!!" 
     exit;; 
    *) 
     print "The input $userinput is invalid." 
     print "Returning to main menu..." 
     print "\n\n\n";; 
    esac 
    done 

    print "Please enter you're guess." 
    read guessInt 
    while (($guessInt != "q")); 
    do 
    if [$guessInt -lt $x]; 
    then 
     print "Your guess is too low, try again! (q to quit)." 
     tries=tries+1 
    elif [$guessInt -gt $x]; 
    then 
     print "Your guess is too high, try again! (q to quit)." 
     tries=tries+1 
    else 
     print "Yay!!! $guessInt is the right number!!!" 
     break 
    fi 
    done 

    print "Your total number of tries were $tries." 
    exit 

任何深入瞭解這個問題,表示讚賞!

回答

1

據我所知,你需要條件的雙括號和一些空白是重要的。你需要的東西,如:

if [[ $guessInt -lt $x ]]; then 

tries也應該從1開始,因爲沒有辦法,你可以不先猜贏。

如果他們的猜測是錯誤的,你也應該在while循環中再次閱讀guessInt,因爲如果你第一次猜錯了,它將會永遠重複(因爲$guessInt的值在循環迭代之間不會改變) 。請參考these shell script syntax examples;它有很多bash的東西,但也有一些體面的ksh的覆蓋面。

+0

謝謝,你的指導幫助了很多! – gmanjake 2012-03-27 23:16:19