對於一個學校項目,我們應該創建一個簡單的程序,該程序從用戶接收關於狗(名稱,品種,年齡和體重)的一些輸入並將其放入ArrayList中。一切似乎都在工作,但爲了測試程序,我想在我的方法setUp()中添加一些狗,以便您可以測試函數,而無需每次都添加新的狗,這就是我迷失的地方!如果我寫的constuctor(狗狗=新的狗( 「亞歷克斯」, 「哈巴狗」,10,10.0)的設置(),我得到錯誤信息:將對象添加到構造函數時遇到問題
The value of the local variable Dog is not used
我試着把構造函數放在「1」的情況下,然後我沒有得到任何錯誤,但是狗不會被添加到數組列表中,而我可以在程序中添加新的狗,我真的不知道下一步該怎麼做。狗需要被添加到狗,構造函數賦值(部分代碼被剪裁成相關的,不用擔心進口或主要)。
class DogReg {
private ArrayList<Dog> allDogs = new ArrayList<Dog>();
private Scanner keyboard = new Scanner(System.in);
private void setUp() {
System.out.print("Hi! Welcome to the Dog register! \n" + "Choose an option between 1-5\n");
System.out.println("1. Register your dog");
System.out.println("2. Increase age");
System.out.println("3. List");
System.out.println("4. Delete");
System.out.println("5. Exit");
}
private void runCommandLoop() {
// Initierar en while-loop som körs under tiden att willRun == true
boolean willRun = true;
while (willRun == true) {
System.out.print("> ");
// Skapar en variabel som konverterar input-sträng till lowerCase
String command = keyboard.next();
switch (command) {
case "1":
// Konstruerar en ny hund in i ArrayList
Dog Dog = new Dog();
// Sparar all input till ArrayList
System.out.print("\nThe name of the dog: ");
Dog.setName(keyboard.next());
System.out.print("The breed of the dog: ");
Dog.setBreed(keyboard.next());
System.out.print("The age of the dog: ");
int age = keyboard.nextInt();
Dog.setAge(age);
System.out.print("The weight of the dog: ");
double weight = keyboard.nextDouble();
Dog.setWeight(weight);
allDogs.add(Dog);
break;
類狗{
private String name;
private String breed;
private int age;
private double weight;
public Dog (String name, String breed, int age, double weight){
this.name = name;
this.breed = breed;
this.age = age;
this.weight = weight;
}
public String getName() {
return name;
}
public String getBreed() {
return breed;
}
public int getAge() {
return age;
}
public double getWeight() {
return weight;
}
public void setName(String name) {
this.name = name;
}
public void setBreed(String breed) {
this.breed = breed;
}
public void setAge(int age) {
this.age = age;
}
我可以在設置()添加一個狗,如果我使用此代碼代替,但我們不應該使用:
Dog Dog = new Dog();
Dog.setName("Bosse");
Dog.setBreed("Mops");
int age = 10;
Dog.setAge(age);
double weight = 10;
Dog.setWeight(weight);
allDogs.add(Dog);
希望這是很清楚,我道歉語法和/或拼寫,英語不是我的第一語言。
我沒有仔細閱讀你的代碼,但是有一件事:'狗狗=新狗();' - 避免這種命名不惜一切代價,它最終會迷惑你,並引入bug 。因此,儘量遵守Java命名約定,它們聲明變量名應以小寫字母開頭,即'Dog dog = new Dog();'。 - 想想這條線會發生什麼:'Dog.setName(keyboard.next());' - 這裏有什麼'狗'?它是你所指的類或變量嗎?編譯器無法知道,並且您稍後可能再也無法再次閱讀您的代碼。 – Thomas
您應該尊重[java命名約定](http://www.oracle.com/technetwork/java/codeconventions-135099.html):'狗狗=新狗();' – jhamon
如果您詢問錯誤原因通過一些代碼發佈完全和完整的錯誤消息,併發布導致錯誤的代碼。不是其他一些代碼。 –