[英]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.