举起手来,我正在为 OU 的 M257 编程问题苦苦挣扎,它是形成性的,没有分数,几天后到期。我无法从测试类中调用构造函数,并且努力了几个小时都无济于事,该类在 Netbeans 6.91 中编译得很好,但构造函数不会创建对象。我做错了什么?
我对第一个问题没问题,但完全卡在这里,显然遗漏了一些重要的东西 - 请指导。我的想法是将文件名传递给类,一旦我知道文件已打开并且扫描仪已初始化,我就可以完成剩下的工作。
===============
/**
* Title: WordCounter class
* Description: M257 TMA01, Q2 - word counter class as described in instructions
* @author Andrew Broxholme
*/
package tma01q2;
import java.io.*;
import java.util.*;
public class WordCounter
{
//Class instance variables
public static int totalWords;
public static int totalEven;
public static int totalOdd;
public static int totalLetters;
private Scanner fileScanner;
String sourceFile;
String line; //The lines of the text file
//Single argument constructor, accepts source filename
public boolean WordCounter(String fileToRead)
{
sourceFile = fileToRead;
try
{
openRead();
while (fileScanner.hasNext())
{
// Process each line of the text file
line = fileScanner.nextLine();
System.out.println(line);
// countWords();
}
return true;
}
catch (Exception exp)
{
return false;
}
finally
{
fileScanner.close();
}
}
//openRead, opens the file and processes each line of the file until finished
private boolean openRead() throws IOException
{
try
{
fileScanner = new Scanner(sourceFile);
return true;
}
catch (Exception exp)
{
return false;
}
}
// More methods to be added
}
/*
* TestWordCounter.
* Description: Tests the WordCounter class as per TMA01q2 instructions
* @author Andrew Broxholme
* V1.0 30th April 2011
*/
package tma01q2;
public class TestWordCounter
{
//Create a WordCounter to process the specified text file.
public static void main(String[] args)
{
String testFile = "haiku.txt";
WordCounter fileStats = new WordCounter(testFile);
}
}
当我尝试编译时,这就是它传回的内容。
Compiling 1 source file to C:\M257\TMA01\TMA01Q2\build\classes
C:\M257\TMA01\TMA01Q2\src\tma01q2\TestWordCounter.java:18: cannot find symbol
symbol : constructor WordCounter(java.lang.String)
location: class tma01q2.WordCounter
WordCounter fileStats = new WordCounter(testFile);
1 error
C:\M257\TMA01\TMA01Q2\nbproject\build-impl.xml:246: The following error occurred while executing this line:
C:\M257\TMA01\TMA01Q2\nbproject\build-impl.xml:113: Compile failed; see the compiler error output for details.
我没有放弃,如果我先找到答案,我会更新问题。
2011 年 5 月 8 日:答案很有帮助,但最后我放弃了这个问题,因为我进一步了解我只是不太了解子类如何从父类(super class)继承,需要尝试一些更简单(对我来说更有意义)的例子来加深我的理解。但问题是 NetBeans 太擅长建议您需要什么,却没有告诉您确切的原因,如果您是一位经验丰富的 Java 开发人员,那很好,但如果您是新手,那就不太好了。
我已经开始(即阅读简介)TMA02 并将给自己整整两个月的时间,一个人认为更明智!
最佳答案
这不是构造函数。删除 boolean
作为返回类型 - 构造函数没有返回类型。所以:
public WordCounter(String fileToRead)
代替
public boolean WordCounter(String fileToRead)
这就是错误告诉您的内容 - 编译器找不到具有该名称的构造函数。
参见:constructors
关于java - 我做错了什么 - 无法从 Main(自定义类)实例化对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5866868/