And*_*ewB 1 java inheritance constructor
举起手来,我正在为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);
}
}
Run Code Online (Sandbox Code Playgroud)
当我试图改变这是它传回来的东西.
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.
Run Code Online (Sandbox Code Playgroud)
我没有放弃这个,如果我先找到答案,我会更新问题.
2011年5月8日:答案是有帮助的,但最终虽然最后我放弃了这个问题,因为我得到的进一步,我意识到我只是不知道子类如何从超类继承并需要尝试一些更简单(和给我更有意义的例子来加深我的理解.但问题是,NetBeans非常善于建议你需要的东西,而不会告诉你它为什么要做它正在做的事情,如果你是一个经验丰富的java开发人员,那就太好了,但是如果你的开始就不那么好.
我已经开始(即阅读简介)了解TMA02并且给我自己整整两个月,更加明智的想法!
这不是构造函数.删除booleanas返回类型 - 构造函数没有返回类型.所以:
public WordCounter(String fileToRead)
Run Code Online (Sandbox Code Playgroud)
代替
public boolean WordCounter(String fileToRead)
Run Code Online (Sandbox Code Playgroud)
这就是错误告诉你的 - 编译器找不到具有该名称的构造函数.
见:构造函数