我目前有2个班级,分别是商店班级和客户班级。客户是商店的子类别。 shop类包含一个大型扫描器方法,该方法将选择一个文件等,然后转到子类客户以获取其readdata方法,该方法用于将扫描文件中的数据分配给客户类的字段,但是它不能像它应该并且我没有这样的元素异常。
这是我的Shop类扫描仪方法
public void readCustomerData()
{
FileDialog myFrame = null;
FileDialog fileBox = new FileDialog(myFrame, "Open", FileDialog.LOAD);
//fileBox.setDirectory("");
fileBox.setVisible(true);
String fileName = fileBox.getDirectory() + fileBox.getFile();
File dataFile = new File (fileName);
Scanner scanner = null;
Customer customer = null;
try{
scanner = new Scanner (dataFile);
}
catch(FileNotFoundException ex)
{
System.err.println("FileNotFound exception");
}
if(scanner != null)
{
while(scanner.hasNext())
{
String lineOfText = scanner.nextLine().trim();
if(!lineOfText.startsWith("//") && (lineOfText.length() > 0))
{
Scanner scan = new Scanner (lineOfText);
scan.useDelimiter("\\s?,\\s?");
customer = new Customer();
customer.readCustomerData(scan);
storeCustomer(customer);
scan.close();
}
// scan.close();
}
scanner.close();
}
}
这是我的客户读取方法
//@Override
public void readCustomerData(Scanner scan)
{
//super.readCustomerData(scan);
customerID = scan.next();
surname = scan.next();
firstName = scan.next();
otherInitials = scan.next();
title = scan.next();
}
如果我尝试使用@Override时出现语法错误,它不允许我将super.readcustomerdata作为其在主类中的无参数方法来调用
您的代码工作正常。我能想象的唯一问题是您的文件格式不适合代码。这是一个完整的示例:
test.txt:
// New customer data\
// data is customerID, surname, firstName, otherInitials, title
unknown, Newton, David, E, Dr
unknown, Gregson, Brian, R T, Mr
unknown, Evans, David, , Dr
unknown, Smith, Sara, C, Ms
1, Muster, Max, Mr., Dr.
2, Frings, Stefan, , ,
Main.java:
import java.io.File;
import java.util.Scanner;
public class Main
{
public static void readCustomerData(Scanner scan)
{
String customerID = scan.next();
String surname = scan.next();
String firstName = scan.next();
String otherInitials = scan.next();
String title = scan.next();
System.out.printf("%s %s %s %s %s\n",customerID,surname,firstName,otherInitials,title);
}
public static void main(String[] args) throws Exception
{
File dataFile=new File("test.txt");
Scanner scanner = new Scanner(dataFile);
while(scanner.hasNext())
{
String lineOfText = scanner.nextLine().trim();
if(!lineOfText.startsWith("//") && (lineOfText.length() > 0))
{
Scanner scan = new Scanner (lineOfText);
scan.useDelimiter("\\s?,\\s?");
readCustomerData(scan);
scan.close();
}
}
scanner.close();
}
}