If statement is not following its conditional

前端 未结 2 1026
谎友^
谎友^ 2021-01-27 14:40

In my code to roll you just write r and then hit enter but it seems not to read that and go to else that restarts the while loop. The only way to get it to roll is by typing som

相关标签:
2条回答
  • 2021-01-27 15:37

    After looking at the properly indented code (see ghoti's rewritten code segment), I see the top level if-block is

    if [ $choice == r ]; then
        die=... #roll the die
    elif [ $die -eq 1 ]...
    elif [ $die -gt 1 ]...
    else
        do something...
    fi
    

    Problem is, if [ $choice == r ] is true, you will roll the die and skip the rest of elif-else entries. So you will go to the next iteration without doing anything (except for rolling the die)

    One way to fix this is to check $choice and $die as separate if blocks, namely

    if [ $choice == r ]; then
        #roll the die
    else
        #break or something...
    fi
    
    if [ $die -eq 1 ]; then
        #do something
    elif the rest of $die-related checks  
    
    0 讨论(0)
  • 2021-01-27 15:40

    Okay, a few comments about your code.

    • This is really hard to read because of the lack of indenting. When nesting things, indent what is nested. With indents, you can see where your loops start and end, what code belongs to which if/else, etc.
    • In bash, you should always quote your variables to avoid accidental expansion. For example, what happens if someone enters an asterisk (*) instead of an "r"? Your if statement will do wondrous and mysterious things.
    • You're using operators wrong. In bash, using single square brackets with if, you compare string equivalency with a single equals (=), not double. And if you want numerical equality, you have -eq. Though you might want to look at bash's extended tests, using double square brackets. (Check the man page for details.)
    • Try not to use external tools for things that bash can do by itself. bc, for example, is not needed for integer arithmetic.

    So ... all said, here's a code segment of yours, re-written a bit.

    while [ "$pt" -eq 1 ]; do
    
        read -p "Roll or stay (r/s)? " choice
    
        if [ "$choice" = r ]; then
    
            die=$(($RANDOM%6+1))
    
        elif [ "$die" -eq 1 ]; then
    
            p1s=$((p1s - count))
            echo "You rolled a 1. Your score is $p1s"
            echo "$p2 turn now."
            sleep 1 
            count=0 
            pt=2    
    
        elif [ $die -gt 1 ]; then
    
            p1s=$((p1s + die))
            count=$((count + die))
            echo "You rolled a $die. Your score is $p1s"
            pt=1    
    
        else
    

    Note that I'm not making any claims about whether your program logic is sound.

    And what the heck is num.sh? Is it important?

    0 讨论(0)
提交回复
热议问题