I have a txt file and I want to be able to compare input of a name to the names already on the file. I get a message "cannot find symbol" for the array that I have stored the txt file data in. I'm not sure if i am doing something wrong with storing the data in an array or what I need to do in order to get it be able to access the array from my for loop.
I get the error at the aryLines in for(String name : aryLines)
package binarysearch;
import java.io.*;
import java.util.Scanner;
/**
*
* @author Timothy
*/
public class BinarySearch
{
public static void main(String[] args) throws IOException
{
String file_name = "C:/Users/Timothy/Documents/test.txt";
try
{
ReadFile file = new ReadFile(file_name);
String[] aryLines = file.OpenFile();
/*
for(int index = 0; index < aryLines.length; index++)
{
System.out.println(aryLines[index]);
}
*/
}
catch(IOException error)
{
System.out.println(error.getMessage());
}
String newName;
Scanner in = new Scanner(System.in);
System.out.println("Enter a name to compare to list: ");
newName = in.nextLine();
for(String name : aryLines)
{
if(name.equalsIgnoreCase(newName))
{
System.out.println("This name has already been added");
}
else
{
WriteFile data = new WriteFile(file_name, true);
data.writeToFile("/n" + newName);
}
}
}
}
WriteFile class
package binarysearch;
import java.io.*;
import java.util.Scanner;
/**
*
* @author Timothy
*/
public class WriteFile
{
private String path;
private boolean append_to_file = false;
public WriteFile(String file_path)
{
path = file_path;
}
public WriteFile(String file_path, boolean append_value)
{
path = file_path;
append_to_file = append_value;
}
public void writeToFile(String textLine) throws IOException
{
FileWriter write = new FileWriter(path, append_to_file);
PrintWriter print_line = new PrintWriter(write);
print_line.printf("%s" + "%n", textLine);
print_line.close();
}
}
ReadFile Class
package binarysearch;
import java.io.*;
/**
*
* @author Timothy
*/
public class ReadFile
{
private String path;
public ReadFile(String file_path)
{
path = file_path;
}
public String[] OpenFile() throws IOException
{
FileReader read = new FileReader(path);
BufferedReader textReader = new BufferedReader(read);
int numberOfLines = readLines();
String[] textData = new String[numberOfLines];
for(int index = 0; index < numberOfLines; index++)
{
textData[index] = textReader.readLine();
}
textReader.close();
return textData;
}
int readLines() throws IOException
{
FileReader file_to_read = new FileReader(path);
BufferedReader buffer = new BufferedReader(file_to_read);
String aLine;
int numberOfLines = 0;
while((aLine = buffer.readLine()) != null)
{
numberOfLines++;
}
buffer.close();
return numberOfLines;
}
}