2014-05-04 95 views
0

我無法將此程序從if-else語句轉換爲switch語句。任何幫助,將不勝感激。將if-else語句轉換爲switch語句

#!/bin/bash 

for x in [email protected] 
do 
array[$i]=$x 
i=$((i+1)) 
done 


# initial state 
state=S0 


for((i=0;i<${#array[@]};i++)) 
do 

if [ $state == S0 ] 
    then 
    if [ ${array[$i]} == I0 ] 
    then 
    state=S1 
    output[$i]=O1 
    elif [ ${array[$i]} == I1 ] 
    then 
    state=S0 
    output[$i]=O0 
    fi 

    elif [ $state == S1 ] 
    then 
    if [ ${array[$i]} == I0 ] 
    then 
    state=S1 
    output[$i]=O1 
    elif [ ${array[$i]} == I1 ] 
    then 
    state=S0 
    output[$i]=O0 
    fi 
    fi 


    done 
    echo "final state="$state 
    echo "output="${output[@]} 

爲那些誰知道有關腳本..這個腳本有關的有限狀態機..這個腳本有兩種狀態我要轉換爲case語句,因此它可以是可讀的,更快尤其是對大項目不是這樣一。

+1

你有什麼麻煩? – chepner

+0

請勿標記垃圾郵件。這與Linux,Emacs或SQL CASE語句無關。我刪除了無關標籤。 – Chris

回答

2

首先,縮進顯然有助於維護您的代碼。

一個錯誤,在if語句中使用單個括號 - 如果比較左側的變量爲空,則會出現語法錯誤。使用雙括號或在變量周圍使用雙引號。這很重要,因爲你正在接受用戶的輸入,而且你永遠不會知道你會得到什麼。

#!/bin/bash 

for x in "[email protected]"; do 
    array[$i]=$x 
    ((i++)) 
done 

# initial state 
state=S0 

for ((i=0; i<${#array[@]}; i++)); do 
    if [[ $state == S0 ]]; then 
     if [[ ${array[$i]} == I0 ]]; then 
      state=S1 
      output[$i]=O1 
     elif [[ ${array[$i]} == I1 ]]; then 
      state=S0 
      output[$i]=O0 
     fi 
    elif [[ $state == S1 ]]; then 
     if [[ ${array[$i]} == I0 ]]; then 
      state=S1 
      output[$i]=O1 
     elif [[ ${array[$i]} == I1 ]]; then 
      state=S0 
      output[$i]=O0 
     fi 
    fi 
done 
echo "final state="$state 
echo "output="${output[@]} 

我看到你做同樣的事情狀態是S0或S1,這樣你就可以刪除該部分。而且,填充數組變量可以被簡化。離開:

#!/bin/bash 
array=("[email protected]") 
state=S0 

for ((i=0; i<${#array[@]}; i++)); do 
    if [[ ${array[$i]} == I0 ]]; then 
     state=S1 
     output[$i]=O1 
    elif [[ ${array[$i]} == I1 ]]; then 
     state=S0 
     output[$i]=O0 
    fi 
done 

echo "final state: $state" 
echo "output: ${output[*]}" 

考慮到這一切,我真的沒有看到一個案例說明幫助你。但如果你想:

#!/bin/bash 
array=("[email protected]") 
state=S0 # initial state 

for ((i=0; i<${#array[@]}; i++)); do 
    case ${array[$i]} in 
     I0) state=S1; output[$i]=O1 ;; 
     I1) state=S0; output[$i]=O0 ;; 
    esac 
done 

echo "final state: $state" 
echo "output: ${output[*]}"