I am having a logic issue with my UNIX number guessing game. The menu system works just fine (1 for play, 2 to quit, defensive response otherwise). But once in the game I am getting an output as follows:
- OPTIONS:
- (1. Play)
- (2. Exit)
- Enter number 1 or 2.
- 1
- Please enter you’re guess.
- 5
- pgm01[43]: [5: not found [No such file or directory]
- pgm01[47]: [5: not found [No such file or directory]
- Yay!!! 5 is the right number!!!
- Your total number of tries were 0.
Here is the code (FYI this is in the KSH shell). I am guessing I have some sort of syntax error somewhere…
#!/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
Any insight into this issue is appreciated!
As far as I can tell, you need double brackets for conditionals and some whitespace is significant. You need something like:
triesshould also start at 1, since there’s no way you can win without guessing first.You should also read
guessIntagain inside the while loop if their guess is wrong, because if you guess wrong the first time, it will just repeat forever (since the value of$guessIntdoesn’t change between iterations of the loop).Take a look at these shell script syntax examples; it’s got a lot of bash stuff but there’s some decent coverage of ksh as well.