2015-04-05 12 views
-1

Эта программа попросит пользователя ввести файл filename.the, если файл exsist.if не существует, то у них есть возможность создать файл или ввести другое имя файла для поиска. Но кажется, что одно утверждение не выполняется.Почему оператор не выполняется

import java.io.PrintStream; 
import java.util.Scanner; 
import java.io.File; 
import java.io.IOException; 

class usingexist 
{ 
    static Scanner in=new Scanner(System.in); 
    static String select=""; 
    static String search=""; 
    static int x; 

    public static void main(String[] args)throws IOException 
    { 
     x=1; 

     while(x==1) 
     { 
      System.out.println("Please the file name you want to search"); 
      search=in.nextLine(); 

      File f=new File(search); 


      if(f.exists()) // check if file exists 
      { 
       System.out.println("File Found."); 
       x=2; 
      } 
      else if(!f.exists()) // creates file if dont exsist 
      { 
       System.out.println("File Not Found."); 
       System.out.println("Do you want to create the File ? (Y/N)"); 
       select=in.nextLine(); 

       if(select.equals('Y')) 
       { 
       f.createNewFile();   // this statement is not beig executed 
       System.out.println("created succesfully"); 
       x=2; 
       } 

      } 
      else if (select.equals('N')) // prompts the user to enter another file name 
      { 
       x=1; 
      } 
     } 

    } 
} 
+0

f.createNewFile() не выполняется кто-нибудь может help.tnks –

+0

Обучение, как использовать отладчик будет _really_ полезным в будущем. – JonasCz

ответ

7
if(select.equals("Y")) 

поставить двойные кавычки вокруг Y. Вы сравниваете два Strings здесь, а не символы.

+0

танки, которые помогли –

+0

Кроме того, оператор 'if (select.equals (" N ")) должен находиться на ветке else' if (select.equals ("Y")) ', а не' if (! F .exists()) ' –

+0

, где все эти upvotes появились в одно мгновение? : O – luk2302

0

И вы должны изменить часть своей логики кода, поскольку ваши операторы if были вложены неправильно. Возможно, вам стоит взглянуть на ключевое слово break.

if(f.exists()) // check if file exists 
{ 
    System.out.println("File Found."); 
    x=2; 
} 
else // creates file if dont exsist 
{ 
    System.out.println("File Not Found."); 
    System.out.println("Do you want to create the File ? (Y/N)"); 
    select=in.nextLine(); 

    if(select.equals("Y")) 
    { 
     f.createNewFile();   // this statement is not beig executed 
     System.out.println("created succesfully"); 
     x=2; 
    } 
    else if (select.equals("N")) // prompts the user to enter another file name 
    { 
     x=1; 
    } 
} 
+0

ОК спасибо вам большое, ребята –

Смежные вопросы