मेरे पास एक ऐसा कार्य है जिसे करने की आवश्यकता है लेकिन मैं वास्तव में अटक गया हूं।ऑब्जेक्ट्स बनाना एक इनपुट फ़ाइल
मूल रूप से, मैं इस तरह कुछ विरासत संबंधों है:
पशु
पालतू WildAnimal
बर्ड बिल्ली कुत्ता मछली || नाग ईगल
पशु पालतू और जंगली की मूल है जानवर। पालतू पक्षी, बिल्ली, कुत्ते, मछली का अभिभावक है। वाइल्डएनिमल सांप और ईगल के माता-पिता हैं।
कार्य चाहता है कि मैं एक फ़ाइल से इनपुट पढ़ूं जो "input.txt" है और पशु वस्तुओं को बनाते हैं।
"input.txt" की तरह है:
कीवी बर्ड चार्ली ईगल आम मछली काली मिर्च कुत्ते कोण बिल्ली ट्वीटी बर्ड बॉब कुत्ता ज़िगी नाग
मुझे इन नामों की सभी प्राप्त कर सकते हैं लेकिन मैं यह समझ नहीं पाया कि प्रत्येक नाम का प्रतिनिधित्व किस प्रकार की वस्तु का प्रतिनिधित्व करता है।
public static void main(String[] args) throws IOException {
String s ="";
int nameCounter = 0;
Animal[] animals = new Animal[100];
try{
Scanner input = new Scanner(Paths.get("input.txt"));
while (input.hasNext()) {
s = input.next();
Animal animal = new Animal(s);
animals[nameCounter] = animal;
nameCounter += 2;
}
}catch(Exception e){
e.printStackTrace();
}
}
यहाँ पशु वर्ग है:
यहाँ मुख्य विधि है
public class Animal {
private String name;
private int numberOfLegs;
private int numberOfWings;
public Animal(String name){
this.name = name;
numberOfLegs = 4;
numberOfWings = 0;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNumberOfLegs() {
return numberOfLegs;
}
public void setNumberOfLegs(int numberOfLegs) {
this.numberOfLegs = numberOfLegs;
}
public int getNumberOfWings() {
return numberOfWings;
}
public void setNumberOfWings(int numberOfWings) {
this.numberOfWings = numberOfWings;
}
public void talk(){
System.out.printf("<Silence>");
}
public void fly(){
System.out.printf("%s cannot fly", getName());
}
public void run(){
System.out.printf("%s is running", getName());
}
}
अगर आप चाहते हैं मैं सभी अन्य वर्गों में जोड़ सकते हैं, लेकिन मैं नहीं है लगता है कि आपको उनकी आवश्यकता होगी।
[यह] (http://stackoverflow.com/questions/1268817/create-new-class-from-a-variable-in-java) आपकी मदद कर सकता है। – Blobonat
त्वरित स्वीकृति के लिए धन्यवाद! – GhostCat