我的问题:
在ReadFile类中,我有一个
必须从Module Class返回对象的public Module ReadTheFileGetTheModuleName(String fichier)
方法。
在方法中,我从Module Class创建一个模块,但是当我想要返回它时,我有一个错误:模块无法解析为变量。
这是我的代码:
public Module ReadTheFileGetTheModuleName(String fichier){
try{
InputStream ips=new FileInputStream(fichier);
InputStreamReader ipsr=new InputStreamReader(ips);
BufferedReader br=new BufferedReader(ipsr);
String ligne;
while ((ligne=br.readLine())!=null){
if (ligne.contains("module"))
{
/*String[] st = ligne.split(ligne, ' ');
System.out.println("Nom = "+st[1]);*/
int longueur = ligne.length();
ligne = ligne.substring(ligne.indexOf(" "));
ligne = ligne.trim();
System.out.println(ligne);
//putting the name in a Module Class
Module module = new Module();
module.setName(ligne);
System.out.println("nom du module : "+module.getName());
module.setFichier(fichier);
System.out.println("nom du fichier lié au module : "+module.getFichier());
}
chaine+=ligne+"\n";
}
return module; //Here is the line were I have an error
br.close();
}
catch (Exception e){
System.out.println(e.toString());
}
**
有人知道我犯过的错误吗?
答案 0 :(得分:2)
问题是您在module
循环内的if
循环范围内声明了while
变量。这意味着在外部作用域中的return
语句不知道声明。
例如,这段代码会失败:
int outerVariable = 5;
if (outerVariable == 5) {
// Ok: the inner scope can access all variables declared in the outer scopes
int innerVariable = 1 + outerVariable;
}
// Ok: the println call and outerVariable declaration are in the same scope
System.out.println(outerVariable);
// Error: The outer scope can't access a variable declared in a inner scope
System.out.println(innerVariable);
为了修复代码,您需要将module
的声明移动到外部作用域,或将return
移动到内部作用域。移动到外部范围将如下所示:
public Module ReadTheFileGetTheModuleName(String fichier) {
try {
Module module = new Module();
while (...) {
if (...) {
// Set the appropriate module properties
}
}
// Ok: the return statement can now see the module declaration
return module;
} catch (...) {
...
}
// Error: no return statement
}
请注意,您仍然会收到错误,因为您在try-catch块之外没有return语句。你需要决定在这种情况下你会做什么,你可以返回null
或者你可以将module
声明移出try-catch并返回它,如下所示:
public Module ReadTheFileGetTheModuleName(String fichier) {
Module module = new Module();
try {
while (...) {
if (...) {
// Set the appropriate module properties
}
}
} catch (...) {
...
}
return module;
}
答案 1 :(得分:1)
问题在于您在嵌套范围内声明module
变量,但之后尝试在该范围之外使用它:
while (...) {
if (...) {
Module module = ...;
}
}
return module;
如果while
或if
条件从未评估为true
,您会发生什么?如果你想在这种情况下返回null
(或其他一些默认值),那很简单 - 只需在循环之前声明它:
Module module = ...;
while (...) {
if (...) {
module = ...;
}
}
return module;
或许你应该真的在return
语句中移动if
语句:
while (...) {
if (...) {
Module module = ...;
...
return module;
}
}
// Work out what you want to do here
这与所涉及的不同类有 nothing - 它只是 关于范围。
答案 2 :(得分:0)
另一种选择是在创建对象时在循环内返回
然后在循环之外,你将不得不返回null
;