簡體   English   中英

為什么不執行語句

[英]Why statement is not being executed

該程序要求用戶輸入文件名,該程序搜索文件是否存在,如果不存在,則可以選擇創建文件或輸入另一個文件名進行搜索。 但是似乎一條語句沒有被執行。

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;
            }
      }

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

Y放在雙引號周圍。 您在這里比較兩個Strings ,而不是字符。

由於您的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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM