【发布时间】:2015-11-06 00:08:43
【问题描述】:
注意:这是一个作业,我要求被推向正确的方向,这也是一个关于技术而不是逻辑的问题。
所以我有一个名为 AnimalHospital 的类,并在构造函数中将文件名字符串作为参数:
public AnimalHospital(String inputFile) throws FileNotFoundException {
// this is required
在构造函数中,我读入了一个通过我的 main 放置的文件,构造函数应该能够读取这个文件。我的问题是我需要使用构造函数中代表扫描仪的变量,在同一类中的另一个方法中。这个类不应该有任何变量,所以我不确定该怎么做。
这里是 AnimalHospital 类:
import java.util.*;
import java.io.*;
public class AnimalHospital {
public AnimalHospital(String inputFile) throws FileNotFoundException {
Scanner input = new Scanner(new File(inputFile));
// how do I get input, into printPetInfoByName()?
}
public void printPetInfoByName(String petName){
// this is only here to show you that I need input in order for
// the program to work
String pName = "";
String oName = "";
String color = "";
String hLength = "" ; // for cat only
String size = ""; // dog only
String dog = "";
String bird = "";
/* This is how my file looks that is being read in
CAT
Ginger Owen Brown female medium
CAT
Busker Samantha male short*/
while(!(input.next().equals("END"))) {
if(input.next().equals("CAT")) {
pName = input.next(); // searching for inserted name
if(pName.equals(petName)) { // if found
oName = input.next();
color = input.next();
hLength = input.next();
Cat cat = new Cat(pName, oName,color, hLength);
// have to grab every word in the line to get each variable
cat.toString();
}
}
if(input.nextLine().equals("DOG")){
pName = input.next();
if(pName.equals(petName)) {
oName = input.next();
color = input.next();
size = input.next();
Dog d = new Dog(pName, oName, color, size);
// have to grab every word in the line to get each variable
d.toString();
}
}
if(input.nextLine().equals("BIRD")){
pName = input.next();
if(pName.equals(petName)){
oName = input.next();
color = input.next();
//size = input.next();
Bird b = new Bird(pName, oName, color);
//have to grab every word in the line to get each variable
b.toString();
}
}/*else{
throw new IllegalArgumentException("Pet Not Found." );
}*/
}
}
这是我的测试仪:
public class Tester {
public static void main (String[]args)throws FileNotFoundException {
AnimalHospital a = new AnimalHospital("data.txt");
a.printPetInfoByName("Ginger");
}
}
我觉得这是一个非常简单的问题,但我不知道如何解决它。
【问题讨论】:
-
可能您打算将 Scanner 作为方法参数传递给这些附加方法。一些额外的代码会有所帮助。
-
好吧,你不能使用
input,因为它的范围是构造函数。 -
不声明实例变量这是不可能的。
-
也许您对作业的理解有误?