这是要求用户输入其信息然后运行checkID(); 将文件中已有的ID与用户输入进行比较
public static void newRecord()
{
System.out.println("Enter your full name: ");
name = input.nextLine();
name = input.nextLine();
System.out.println("Enter your age: " );
age = input.nextInt();
input.nextLine();
System.out.println("Enter your id: ");
id = input.nextInt();
checkID();
if(checkID())
{
start();
}
else
{
System.out.println(id);
addRecords();
}
}
这是我检查身份证的地方。我检查ID:启动的位置然后查找id的值,但是它没有检测到文件中的ID并且它创建了精确的Id,而不是告诉用户id已经被记录
public static boolean checkID()
{
Scanner y = new Scanner("Names.txt");
while(y.hasNextLine())
{
final String idChecker = y.nextLine();
if(idChecker.startsWith("ID: ") && idChecker.substring(4).equals(String.valueOf(id)))
{
System.out.println("Sorry, this ID has already been taken, please try again.");
y.close();
return true;
}
}
y.close();
return false;
}
答案 0 :(得分:0)
File
对象传递给Scanner
而不是文件名。addRecords()
,即一旦您的while
循环退出,进入if
区块。equals()
代替contains()
,否则如果11
已经存在,您就无法创建身份1
!理想情况下,您的checkID()
方法应返回boolean
表示已存在的ID,然后调用方应相应地调用start()
或addRecords()
。
public static boolean checkID()
{
try {
Scanner y = new Scanner(new File("Names.txt")); // pass File instance
while(y.hasNextLine())
{
final String idChecker = y.nextLine();
if(idChecker.startsWith("ID: ") &&
idChecker.substring(4).equals(String.valueOf(id)))
{
System.out.println(
"Sorry, this ID has already been taken, please try again.");
y.close();
return true;
}
}
y.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return false;
}
请注意,我完成后会调用Scanner#close()
。您的newRecord()
方法应该类似于
public static void newRecord()
{
System.out.println("Enter your full name: ");
name = input.nextLine();
System.out.println("Enter your age: " );
age = input.nextInt();
System.out.println("Enter your id: ");
id = input.nextInt();
System.out.println(id);
if(checkID())
{
start();
}
else
{
addRecords();
}
}