2017-02-05 12 views
0

2番目のwhileループ(promptAddAgain)を追加した後にDVDオブジェクトを返すことに問題があります。この関数は、ループが追加されている間に、この前に完全に機能します。コンパイル時のエラー - symbol:variable currentDVDを見つけることができません。メソッド内のループ中に入れ子にした後に値を返すことができません

public DVDs getNewDVDInfo() { 
    boolean keepRunning = true; 
    boolean promptAddAgain = true; 
    while (keepRunning) { 
     String title = input.readString("Please enter the move title."); 
     String releaseDate = input.readString("Please enter the release date."); 
     String MPAArating = input.readString("Please enter the MPAA rating."); 
     String directorName = input.readString("Please enter the director name."); 
     String studio = input.readString("Please enter the name of the studio."); 
     String userRating = input.readString("Please type in any comment you would " 
       + "like to leave for this movie below."); 

     DVDs currentDVD = new DVDs(releaseDate, MPAArating, directorName, studio, userRating); 
     currentDVD.setTitle(title); 

     while (promptAddAgain) { 
      String userAns = input.readString("Would you like to add another DVD to the library?"); 
      if (userAns.equals("n")) { 
       input.print("Thank you. Returning to main menu."); 
       keepRunning = false; 
       promptAddAgain = false; 
      } else if (userAns.equals("y")) { 
       input.print("\n"); 
      } else { 
       input.print("Unknown input, please try again."); 
       keepRunning = false; 
      } 
     } 
    } 
    return currentDVD; //<--- error 
} 

答えて

1

currentDVDは現在、外側のwhileループ内で定義されているため、エラーが生じているが、それがスコープ外になった後、あなたは、そのループの外、それを参照しています。上記の方法で、発信者がそのに注意する必要がありますのでごgetNewDVDInfo()方法は、nullを返すかもしれないことも可能であることに留意してください

DVDs currentDVD = null; 
while (keepRunning) { 
    ... 
} 
return currentDVD; 

:この問題を解決する一つの方法は、最初whileループの前にcurrentDVDを宣言することです。

+0

問題を修正しました。そのスコープには注意を払っていませんでした。ありがとう! – FeCH

+1

@FeCH upvoteは可能ですか? –

+0

さて、ちょうどやった。 ;) – FeCH

関連する問題