简体   繁体   English

为什么不执行语句

[英]Why statement is not being executed

This program ask a user to enter a filename.the program searches if the file exsist.if not exsist they have the option to create the file or enter another filename to search. 该程序要求用户输入文件名,该程序搜索文件是否存在,如果不存在,则可以选择创建文件或输入另一个文件名进行搜索。 But it seems that one 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"))

put double quotes around the Y . Y放在双引号周围。 You are comparing two Strings here, not characters. 您在这里比较两个Strings ,而不是字符。

And you should change some of your code logic since your if statements were nested incorrectly. 由于您的if语句嵌套不正确,因此您应该更改一些代码逻辑。 YOu should maybe take a look at the break keyword as well. 您也许也应该看看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