gpt4 book ai didi

java - 将用户输入与文本文件中的字符串进行比较

转载 作者:行者123 更新时间:2023-12-02 02:54:10 24 4
gpt4 key购买 nike

我试图将用户的名字和姓氏与文本文件中的名称进行比较,如果匹配,则生成输出。如果名称不匹配,则程序会给出错误。当我运行程序时,我不断收到错误“线程“main”中的异常 java.lang.ClassCastException:java.io.File 无法转换为 java.lang.Readable” 在 ReadFile.main(ReadFile.java:24)"

public class ReadFile {

public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
@SuppressWarnings("resource")
Scanner Input = new Scanner(System.in);
System.out.print("Enter First Name:");
String FirstName = Input.nextLine();

@SuppressWarnings("resource")
Scanner Input1 = new Scanner(System.in);
System.out.print("Enter Last Name:");
String LastName = Input1.nextLine();

String UserFile = "UserFile.txt";
@SuppressWarnings("resource")
//BufferedReader inputStream =new BufferedReader(new FileReader("myfile.txt"));
Scanner inputStream = new Scanner((Readable) new File(UserFile));


String line = inputStream.nextLine();
inputStream.useDelimiter("[\\r,]");
while (inputStream.hasNext())
{
//contains name
//String line = inputStream.next();

//split names
String [] arrayName = line.split(",");
String FName = arrayName[0];
String LName = arrayName[1];

if(FirstName.equals(FName) && LastName.equals(LName))
{
System.out.println("You are Logged IN");
}

else
{
System.out.println("You need to create a new account");
}

}


}



}

最佳答案

您正在将文件转换为可读。

Scanner inputStream = new Scanner((Readable) new File(UserFile));

删除它并用 try 和 catch 包围该语句。

Scanner inputStream = null;
try
{
inputStream = new Scanner(new File(UserFile));
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
if(inputStream != null)
{
inputStream.close();
}
}

关于java - 将用户输入与文本文件中的字符串进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43373857/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com