Get object name of a class from the user in Java -
i want user enter name of object used in code. example, if have class
public class person{ ....... }
now instead of me creating object specific name like
person student;
i want user enter name object maybe teacher, , object teacher of class person created. not know if possible in java, many of solutions looked using map, explanations not clear enough me new java.
so, if explain how can done code snippets wonderful.
also please explain how hashmaps work in java , if can used implement problem above. grateful if explained code examples
it's not possible. names of local variables not persistent in compiled class file. names of fields there, part of api, have modify class file runtime - , not want.
with hashtable, may done this:
hashtable<string, person> hashtable = new hashtable<>(); hashtable.put("student", new person());
then may "variable" by:
person person = hashtable.get("student");
when guess trying do, more helpful example:
import java.util.hashtable; import java.util.scanner; public class test { public static class person { public final string name; public final int age; public person(string name, int age) { this.name = name; this.age = age; } @override public string tostring() { return "name: " + name + ", age: " + age; } } public static class personslist { private hashtable<string, person> persons = new hashtable<string, test.person>(); public void addperson(person person) { this.persons.put(person.name, person); } public person findperson(string name) { return persons.get(name); } @override public string tostring() { return persons.tostring(); } } public static void main(string[] args) { personslist personslist = new personslist(); scanner scanner = new scanner(system.in); while (scanner.hasnextline()) { string line = scanner.nextline(); if (line.equals("end")) { break; } try { string[] parts = line.split(" "); string name = parts[0]; int age = integer.valueof(parts[1]); personslist.addperson(new person(name, age)); } catch (numberformatexception e) { system.out.println("age must decimal non-floating-point number."); } catch (arrayindexoutofboundsexception e) { system.out.println("you must enter both name , age"); } } scanner.close(); system.out.println(personslist); } }
Comments
Post a Comment