0
注意:這是一項任務,我要求推向正確的方向,這也更多的是關於技術而不是邏輯的問題。將Scanner從構造函數中獲取到類中的方法?
所以我有這個類叫做AnimalHospital,並在構造一個文件名字符串作爲參數:
public AnimalHospital(String inputFile) throws FileNotFoundException {
// this is required
在構造函數中,我在我已經通過我的主要放置在文件讀取,構造函數應該能夠讀取這個文件。我的問題是我需要使用代表掃描器的構造函數中的變量,而使用同一個類中的另一個方法。這個班不應該有任何變數,所以我不確定要做什麼。
這裏是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");
}
}
我覺得好像這是一個很簡單的問題,但我不知道如何解決它。
可能你意在通過掃描儀作爲方法參數的那些附加的方法。一些額外的代碼會有幫助。 – markspace
那麼,你不能使用'輸入',因爲它的**範圍**是構造函數。 – Alexander
沒有聲明一個實例變量,這是不可能的。 – Alexander