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 smallList = new ArrayList();
while(input.hasNextLine()){
line = input.nextLine;
if(line.equals("")){
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?
解决方案
Scanner input = new Scanner (inFile);
input is local to the constructor, you cannot access outside of it, and you are trying to access in makeSmallerLists() method. Make it as a instance member, So that it available through out the class other than static context.
public class Grocery{
Scanner input;
and in constructor
public Grocery(){
File inFile = new File ("lists.txt");
input = new Scanner (inFile);