2011-01-12 2 views
1
   String filename1; //file name to write to 

    //get the file name to write to 
    System.out.println("\nEnter the filename for the file where the information will be stored:"); 
    filename1=keyboard.nextLine(); 
       File title1= new File(filename1); 

    while (title1.exists()) //make sure the file doesn't exist 
    { 
     System.out.println("The file " + filename1 +" already exists."); 
     System.out.println("Please choose another name."); 
     System.out.println("Enter the filename:"); 
     filename1=keyboard.nextLine(); 
    } 

存在しないファイル名を入力してもループが繰り返されると、存在するファイル名によってループがトリガーされます。どうして?宿題:ファイルが存在しないことを確認するためにループを使用する

答えて

0

File title1= new File(filename1); 
while (title1.exists()) //make sure the file doesn't exist 
{ 
    System.out.println("The file " + filename1 +" already exists."); 
    System.out.println("Please choose another name."); 
    System.out.println("Enter the filename:"); 
    filename1=keyboard.nextLine(); 
    title1= new File(filename1); 
} 
1

実際には各繰り返しで新しいファイルの存在をテストしているわけではありません.tex1の.exists()をループの前にインスタンス化されているので、ループの繰り返しごとにテストするだけです。

0

whileループの中で、どこに変更するのではなく、title1です。

0

title1がまだ古いファイル(既に存在するファイル)を指しているため、ループは終了しません。

String filename1; //file name to write to 

//get the file name to write to 
System.out.println("\nEnter the filename for the file where the information will be stored:"); 
filename1=keyboard.nextLine(); 
File title1= new File(filename1); 

while (title1.exists()) //make sure the file doesn't exist 
{ 
    System.out.println("The file " + filename1 +" already exists."); 
    System.out.println("Please choose another name."); 
    System.out.println("Enter the filename:"); 
    filename1=keyboard.nextLine(); 

    title1 = new File(filename1); 
} 
0

なぜ:あなたは、変数を更新する必要がありますか?

title1を更新していないためです。実際には、ユーザーが提供する最初の(存在しない)ファイル名のテストを続けます。


コードには別の(あまり目立たない)バグがあります。ユーザーがEOF文字(^ Dなど)を入力するとreadLine()への呼び出しはnullを返し、コードはNullPointerExceptionという結果になり、ヌル参照でexists()を呼び出しようとします。存在しないかではない場合は、常に最初のファイルをチェックし、新しいファイル名でそれを初期化する必要があり

0

あなたがないとき:あなたがやっている

filename1=keyboard.nextline(); 

すべての文字列値を更新していますfilename1で開催されます。 title1を作成するときにfilename1を使用したにもかかわらず、その関係はあなたが思っているように維持されません。あなたがする必要がどのような

新しいファイル名で新しいファイルを作成して、再度同じテストを行いますされています

filename1=keyboard.nextLine(); 
// re-create file 1 with the new filename stored in filename1 

また、制御変数を格納するために、一般的に進歩して(かどうかと言うビット

Boolean fileExists = title1.exists(); 

while(fileExists) { 
    .... 
} 

このようなあなたのコードを見て何かになります:

filename1=keyboard.nextLine(); 
// re-create file 1 with the new filename stored in filename1 
// update the fileExists variable to reflect if the new file exists or not 
をする方法を独自の変数にループを)やって、というよりも呼び出して続行しません
関連する問題