2017-01-04 7 views
0

PowerShell 5.0クラスの実験で、Rosetta Codeで安定した結婚問題のJavaScriptコードを翻訳しようとしました。それは非常にまっすぐなようだが、2番目のメソッド(ランク)はエラーを返す:すべてのコードパスがメソッド内の値を返すわけではない。 $this.Candidates.Count0であれば、ノーリターンが実行されませんのでPowerShell 5.0クラスメソッド "すべてのコードパスがメソッド内で値を返すわけではありません"

class Person 
{ 
    # --------------------------------------------------------------- Properties 
    hidden [int]$CandidateIndex = 0 
    [string]$Name 
    [person]$Fiance = $null 
    [person[]]$Candidates = @() 

    # ------------------------------------------------------------- Constructors 
    Person ([string]$Name) 
    { 
     $this.Name = $Name  
    } 

    # ------------------------------------------------------------------ Methods 
    static [void] AddCandidates ([person[]]$Candidates) 
    { 
     [Person]::Candidates = $Candidates 
    } 

    [int] Rank ([person]$Person) 
    { 
     for ($i = 0; $i -lt $this.Candidates.Count; $i++) 
     { 
      if ($this.Candidates[$i] -eq $Person) 
      { 
       return $i 
      } 

      return $this.Candidates.Count + 1 
     } 
    } 

    [bool] Prefers ([person]$Person) 
    { 
     return $this.Rank($Person) -lt $this.Rank($this.Fiance) 
    } 

    [person] NextCandidate() 
    { 
     if ($this.CandidateIndex -ge $this.Candidates.Count) 
     { 
      return $null 
     } 

     return $this.Candidates[$this.CandidateIndex++] 
    } 

    [int] EngageTo ([person]$Person) 
    { 
     if ($Person.Fiance) 
     { 
      $Person.Fiance.Fiance = $null 
     } 

     return $this.Fiance = $Person 
    } 

    [void] SwapWith ([person]$Person) 
    { 
     Write-Host ("{0} and {1} swap partners" -f $this.Name, $Person.Name) 
     $thisFiance = $this.Fiance 
     $personFiance = $Person.Fiance 
     $this.EngageTo($personFiance) 
     $Person.EngageTo($thisFiance) 
    } 
} 

答えて

1

エラーです。

2番目のリターンはforループの外にあるべきですか?

現在の方法で、最初の候補と一致しない場合は、$this.Candidates.Count + 1が返されます。

[int] Rank ([person]$Person) 
{ 
    for ($i = 0; $i -lt $this.Candidates.Count; $i++) 
    { 
     if ($this.Candidates[$i] -eq $Person) 
     { 
      return $i 
     } 
    } 
    return $this.Candidates.Count + 1 
} 
+0

非常に素早い返信をいただきありがとうございます。私は「単純な」直接の翻訳をしないようにと思います。私は自分の誤りを認め、私はそれを繰り返さない。 –

関連する問題