I know a similar problem may have been presented here before, but i cannot find the answer on my own. To preface this, I have already found a workaround but would like to know why calling a constructor is failing. I will show the failed code and then working.
This code is a simple file analyzer, it reports the first last and ~middle (not exact) entries in a txt file. One of the requirements is recieving an argument from commandline.
Thanks for your time.
FAILED:
$ javac DataAnalyzerTester.java
DataAnalyzerTester.java:11: cannot find symbol
symbol : constructor DataAnalyzer(java.lang.String)
location: class DataAnalyzer
analyze = new DataAnalyzer(args[0]);
-----------^
//DataAnalyzerTester.java
import java.util.*;
import java.io.*;
public class DataAnalyzerTester
{
public static void main(String[] args)
{
DataAnalyzer analyze;
analyze = new DataAnalyzer(args[0]);
//analyze.setFile(args[0]);
System.out.println(analyze.min());
System.out.println(analyze.max());
System.out.println(analyze.avg());
}
}
//DataAnalyzer.java
import java.util.*;
import java.io.*;
public class DataAnalyzer
{
public void DataAnalyzer(String fileN)
{
try
{
reader = new FileReader(fileN);
Scanner in = new Scanner(reader);
while(in.hasNextLine())
{
fileContent.add(in.nextLine());
}
}
catch(IOException exception)
{
System.out.println("File not found. Try again Dumbass.");
}
}
public void setFile(String fileN)
{
try
{
reader = new FileReader(fileN);
Scanner in = new Scanner(reader);
while(in.hasNextLine())
{
fileContent.add(in.nextLine());
}
}
catch(IOException exception)
{
System.out.println("File not found. Try again Dumbass.");
}
}
public String min()
{
return fileContent.get(0);
}
public String max()
{
return fileContent.get(fileContent.size() - 1);
}
public String avg()
{
return fileContent.get((int) fileContent.size() / 2);
}
private FileReader reader;
private ArrayList<String> fileContent = new ArrayList<String>();
}
Basically the above version does not work, but I added a setFile method to do the same thing as the constructor. My question then is why can i not call the constructor in this way? Thanks again.
A constructor should not specify a return type – this combined with a name matching the class is how the compiler recognizes it as a constructor. So instead of:
write:
More information: http://download.oracle.com/javase/tutorial/java/javaOO/constructors.html