0
Im trying to make a list of objects and print them out in java. I get error in multiple places.
import java.util.* ; class Animal { ArrayList<String> animalList = new ArrayList<String>(); String type_of_animal ; String name ; int age ; public Animal(String type_of_animal, String name, int age){ } public static void main(String[] args) { Animal lion = new Animal("lion", "Simba", 10); animalList.add(lion);<----error for(String a : animalList){ System.out.println(a.type_of_animal, a.name, a.age) ;<---error } } }
3 Réponses
+ 2
Lenoname 
You have declared list of String but adding object of Animal class which is wrong
type_of_animal is a field of Animal class not String class so you cannot print like that
your constructor is incomplete
+ 2
Lenoname 
println() method except only one arguments so you have to use seperate println method
You cannot access non-static members in static methods
//like this?(i changed type_of_animal to aType), how can i print out then?
import java.util.*;
class Animal {
    String aType;
    String name;
    int age;
  
    public Animal(String aType, String name, int age) {
        this.aType = aType;
        this.name = name;
        this.age = age;
    }
  
    public static void main(String[] args) {
        Animal lion = new Animal("lion", "Simba", 10);
        
        List<Animal> animalList = new ArrayList<>();
        
        animalList.add(lion);
    
        for(Animal a : animalList) {
            System.out.println(a.aType);
            System.out.println(a.name);
            System.out.println(a.age);
        }
    }
}
0
like this?(i changed type_of_animal to aType), how can i print out then?
import java.util.* ;
class Animal {
  ArrayList<Animal> animalList = new ArrayList<>();
  String aType ; ;
  String name ;
  int age ;
  public Animal(String aType, String name, int age){
    this.aType = aType ;
    this.name = name ;
    this.age = age ;
  }
  public static void main(String[] args) {
    Animal lion = new Animal("lion", "Simba", 10);
    animalList.add(lion);
    for(Animal a : animalList){
      System.out.println(a.aType, a.name, a.age) ;
    }
  }
}



