I have this code that is taking a text file and turning it into a string and then separating parts of the string into different elements of an arraylist.
import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;
public class Grocery{
public Grocery(){
File inFile = new File ("lists.txt");
Scanner input = new Scanner (inFile);
String grocery;
{
grocery = input.nextLine();
}
}
public void makeSmallerLists(){
String listLine;
String line;
ArrayList<String> smallList = new ArrayList<String>();
while(input.hasNextLine()){
line = input.nextLine;
if(line.equals("<END>")){
smallList.add(listLine);
} else{
listLine = listLine + "\n" + line;
}
}
}
}
However when I try to compile this it gives me two errors:
javac Message.java Message.java:31: cannot find symbol symbol : variable input location: class Message while(input.hasNextLine()){ ^ Message.java:32: cannot find symbol symbol : variable input location: class Message line = input.nextLine; ^
How do I fix this? I really don't know what's wrong.
I fixed that and now my error says $ javac Message.java Message.java:34: cannot find symbol symbol : variable nextLine location: class java.util.Scanner line = input.nextLine; ^
^
Now what is wrong?
That is because the Scanner object
input
has been declared inside your constructor(local scope of the constructor) and thus its not visible in yourmakeSmallerLists()
. You need to declare it as an instance variable so that it would be accessible in all the methods of the class.input
is local to the constructor, you cannot access outside of it, and you are trying to access inmakeSmallerLists()
method. Make it as a instance member, So that it available through out theclass
other thanstatic
context.and in constructor
One solution is to have a class member of type
Scanner
:And in the constructor, construct it:
Now
input
is not limited to the scope of the constructor, it'll be accessible through the whole class.Consider this example:
input
is not accesible outside the constructor...it's declared insisde the constructorYou have variable scope problem. You can't get access a field outside of scope. Declare Scanner as globally, outside of costructor.
Also append method bracket
()
.