2014-05-04 96 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[*]}"