My problem :
In a ReadFile class, I have a
public Module ReadTheFileGetTheModuleName(String fichier)
method which has to return an object from a Module Class.
In the method, I create a module from the Module Class but when I want to return it, I have an error : module cannot be resolved to a variable.
Here is my code:
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());
}
**
Do someone knows the possible mistake I have made ?
The problem is that you're declaring the module
variable in a nested scope, but then trying to use it outside that scope:
while (...) {
if (...) {
Module module = ...;
}
}
return module;
What would you expect to happen if the while
or if
conditions never evaluated to true
? If you want to return null
(or some other default value) in that case, that's easy - just declare it before the loop:
Module module = ...;
while (...) {
if (...) {
module = ...;
}
}
return module;
Or perhaps you should really be moving the return
statement inside the if
statement:
while (...) {
if (...) {
Module module = ...;
...
return module;
}
}
// Work out what you want to do here
This has nothing to do with different classes being involved - it's just about scope.
See more on this question at Stackoverflow