代码应该从文本文件的一行文本中读取并处理它,将其添加到已处理行的数组中,然后返回数组
但是当我尝试返回数组时,我一直收到错误。我假设我在代码正文中做错了什么
static public Media[] importMedia(String fileName){
try {
FileReader fileReader = new FileReader(fileName);
BufferedReader br = new BufferedReader(fileReader);
System.out.println("Reading metadata file: "+fileName);
int len=new Integer(br.readLine()); //read number of entries in file
//read line in text file
//process line using createMedia
//add media to array of media objects
Media media = createMedia(br.readLine());
Media[] newMedia = new Media[len];
for(int i = 0;i<=len;i++){
newMedia[i] = media;
}
//return newMedia
br.close();
} catch (IOException e){
System.out.println("IO error reading "+fileName);
}
return newMedia;
}
答案 0 :(得分:1)
问题在于,您尝试返回的数组位于try-catch块中,并且无法在return关键字外部访问。
尝试此更新:
var xml = "<?xml version='1.0' encoding='utf-8'?><campaign guid='799223B1-24A7-4F01-8DAE-632E6F68F845'><LeaderBoard><Target Rank='1' TotalScore='138000' FirstName='Shane' LastName='Foster' TargetCompanyName='[Acme]' DisplayName=''>Hello World</Target></LeaderBoard></campaign>",
xmlDoc = $.parseXML(xml),
$xml = $(xmlDoc),
$title = $xml.find("Target");
alert($title.text());
答案 1 :(得分:0)
对我而言,最直接的事情是你的返回变量是在try的主体内声明的。如果在创建变量之前抛出IOException(很可能因为所有IO都在它之上),所以不会返回newMedia。
将newMedia的声明移出try,并在try和catch中初始化它。
static public Media[] importMedia(String fileName){
Media[] newMedia;
try {
FileReader fileReader = new FileReader(fileName);
BufferedReader br = new BufferedReader(fileReader);
System.out.println("Reading metadata file: "+fileName);
int len=new Integer(br.readLine()); //read number of entries in file
//read line in text file
//process line using createMedia
//add media to array of media objects
Media media = createMedia(br.readLine());
newMedia = new Media[len];
for(int i = 0;i<=len;i++){
newMedia[i] = media;
}
//return newMedia
br.close();
} catch (IOException e){
System.out.println("IO error reading "+fileName);
newMedia = null;
}
return newMedia;
}