I want the user to enter the name of the object to be used in the code. For example, if I have a class
public class Person{
.......
}
now instead of me creating an object with a specific name like
Person student;
I want the user to enter the name for the object maybe like teacher, and then an object teacher of the class person will be created.
I do not know if this is even possible in java, many of the solutions I looked up were using a map, but the explanations were not clear enough for me as I am new to java.
So, if anyone could explain how it can be done with code snippets it would be wonderful.
Also please explain how hashmaps work in java and if they can be used to implement the problem above. I would be really grateful if explained with code examples
It's not possible. Names of local variables are not even persistent in the compiled Class file. Names of fields are there, as it is the part of API, but you would have to modify the Class file runtime - and that is not what do you want.
With Hashtable, it may be done like this:
Hashtable<String, Person> hashtable = new Hashtable<>();
hashtable.put("student", new Person());
Then you may get your "variable" by:
Person person = hashtable.get("student");
When I guess what you are trying to do, this is some 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 be an decimal non-floating-point number.");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("You must enter both name and age");
}
}
scanner.close();
System.out.println(personsList);
}
}
Related
have a question about this code. How can I add information to an existing element? For example in the beginning the machine asks the user to give a name. If I give the name "Harry" the machine will just say "the student name is correct" but I want also to see the age of that student and in general some information. So my question is how can I add informations for each student? Here is my code so far. Thanks in advance!
package test;
import java.util.*;
public class readStudents {
public static void main(String []args) {
ArrayList<String> arrlstStr = new ArrayList<String>(); //Declaring ArrayList
arrlstStr.add("Malte");
arrlstStr.add("Timo");
arrlstStr.add("Harry");
arrlstStr.add("Julian");
arrlstStr.add("Musa");
arrlstStr.add("Mirnes");
arrlstStr.add("Daniel");
arrlstStr.add("David");
arrlstStr.add("Nico");
arrlstStr.add("Ranya");
arrlstStr.add("Xuan");
arrlstStr.add("Sören");
arrlstStr.add("Mark");
arrlstStr.add("Salomon");
arrlstStr.add("Leon");
arrlstStr.add("Niklas");
arrlstStr.add("Tobias");
System.out.println("Enter the name of the student: ");
Scanner scanner = new Scanner(System.in);
String student = scanner.nextLine();
if (arrlstStr.contains(student)) {
System.out.println("This student name is correct");
}
else {
System.out.println("You gave a wrong name");
}
}
}
public class Student {
private String name;
private int age;
// other fields with getter and setter
}
public class StudentFields {
public static void main(String []args){
ArrayList<Student> arrlstStr = new ArrayList<Student>(); //Declaring ArrayList
Student s1 = new Student();
s1.setName("R1");
s1.setAge(20);
arrlstStr.add(s1);
arrlstStr.add(s2);
}
}
A very simple thing to do :)
You will agree with me that, array list is a collection of list of elements. This elements in your case were pre-defined. What I would suggest is that you have to also define the information you want any element to have. For example; student name 'Harry' should have a piece of corresponding information like age pointing to it; student_age; e.g. Harry_age set to '34'. something like this:
arrlstStr.add("Harry");
arrlstStr.add("Harry_age")
assigning value to the element
Harry_age = 34;
The above illustration is to guide you.
Once you have defined that, make you use of your if-statement. The pseudo-code is;
IF student name is "Harry" THEN
DISPLAY 34 (Harry's age)
This should work. Is just simple logic.
As per your requirement I would recommend to use map instead of Array list and keep the student name as key and student object as value so on bases of name you can get student information.such as below
public class Student {
private String name;
private int age;
public Student(String name,int age)
{
this.name=name;
this.age=age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
public class StudentData {
public static void main(String []args){
Map<String,Student> studentCollection=new HashMap<String,Student>();
Student student = new Student("Sachin",40);
studentCollection.put(student.getName(),student);
.
.
}
}
Our prof gave us an activity about creating a linked list with another class that has attributes or behavior of last name, first name, age, course, etc.
So my question is if I set a cumulative setter with the following given attributes. if I add it to the linked list will the linked list itself will create one list only with the given attributes? and thus if I search it in the list will the linked list need those attributes to be able to search it?
Here's my code for the class with attributes/behavior. I minimized it only with a little attributes so that it is better to correct it:
class Student2 {
public String lastName;
public String firstName;
public Student2() {
}
public void setlastName(String lastName) {
this.lastName = lastName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public String getFirstName() {
return firstName;
}
public void setInfo() {
Scanner in = new Scanner(System.in);
System.out.println("Enter your LastName here:");
setlastName(in.nextLine());
System.out.println("Enter your FirstName here:");
setFirstName(in.nextLine());
}
}
Here's the code of the main method in which the class with attributes will be called. The menu method will ask the user if he/she wants to add a student or search a student on the list :
public class Project {
public static LinkedList<Student2> list = new LinkedList<Student2>();
public static Student2 info = new Student2();
public static void main(String args[]) {
menu();
}
public static void insert() {
info.setInfo();
list.add(info);
System.out.println("Student added!");
}
public static void search() {
Scanner in = new Scanner(System.in);
System.out.println("Enter the LastName:");
String lastname = in.nextLine();
System.out.println("Enter the FirstName:");
String firstname = in.nextLine();
boolean found = false;
for (Student2 student2 : list) {
if (lastname.equals(student2.lastName) && firstname.equals(student2.firstName)) {
found = true;
break;
}
}
if (found) {
System.out.println(lastname + " found ");
} else {
System.out.println(lastname + " not found ");
}
}
}
No linkedlist will be generic and independent of any behavior. As list doesn't have any information about what object it is going to hold (that is the whole purpose of abstraction). Today, it is student; tomorrow it could be car or burger.
It seems that you don't get the base differences between the classes you are using.
First of all, classes are a model that somehow represent the "real" things you want to work with.
Coming from there: a list is nothing but a generic container of elements. Like a suitcase. You can put many different things into that suitcase, and it doesn't matter (to the suitcase), if you put one shoe into it, or two gloves. It is just a container. And to the contrary: the specifics of the elements in that container should not matter at all to the container.
I have cut out the code to shorten the page but I'm asking how do I change personInterests into its own class. Apologies for the vague question but essentially I want to change personInterests in my Person class to a class where personInterests has multiple variables.
import java.util.ArrayList;
import java.util.*;
public class Person{
private String personName;
private String[] personInterests = new String[3];
public Person(String personName, String[] personInterests){
this.personName = personName;
this.personInterests = personInterests;
}
public void setInterests(String[] personInterests){
this.personInterests = personInterests;
}
public String[] getInterests(){
return personInterests;
}
public String getName(){
return personName;
}
public String toString(){
String result = getName() + " ";
for (String interests : personInterests) {
result += interests + " ";
}
return result;
}
}
This was my idea of how it would work just not sure how I would use this class and call it later on.
import java.util.ArrayList;
import java.util.*;
public class Interests {
private int interestDangerRating;
private String interestName;
private ArrayList<Interests> interestsList = new ArrayList<>();
public Interests (int interestDangerRating ,String interestName){
this.interestDangerRating = interestDangerRating;
this.interestName = interestName;
}
public void addInterests(Interests p){
interestsList.add(p);
}
Interests getInterests(int i){
return interestsList.get(i);
}
}
Any help is appreciated, as I said this code has mostly been taken out and this was an old project already completed just wanted to see if I could change some of the features.
OK so here's what I would do to clean this up for you and make it work. Firstly, think about what you are trying to do. You want to create a Person who has multiple Interests, right? So the Interest class, going by your above example, can be changed to be a typical Java object class as follows:
public class Interest {
private int dangerRating;
private String name;
public Interest (int dangerRating, String name) {
this.dangerRating = dangerRating;
this.name = name;
}
public int getDangerRating() {
return dangerRating;
}
public String getName() {
return name;
}
}
So now we've an Interest class set up where you can set a name for your interest and a danger rating. What we need to do, now, is edit your Person class so as you can store a list of interests for each Person you create.
import java.util.ArrayList;
public class Person{
private String name;
private ArrayList<Interest> interests = new ArrayList<Interest>();
public Person(String name, ArrayList<Interest> interests) {
this.name = name;
this.interests = interests;
}
public void addInterest(Interest newInterest) {
interests.add(newInterest);
}
public Interest getInterest(int indexOfInterest) {
return interests.get(indexOfInterest);
}
public ArrayList<Interest> getInterests() {
return interests;
}
public String getName() {
return name;
}
public String toString() {
String result = getName() + " ";
for(Interest interest : interests) {
result += interest.getName() + "(" + interest.getDangerRating() + ")" + " ";
}
return result.trim();
}
}
This allows you to set an initial list of all interests for your new Person and, from there, you can add new interests, get all interests or get any individual interest.
Hope this helps to clarify for you how this should all fit together!
So now it's time to instantiate everything. Lets create some Interestobjects which we will use:
Interest golf = new Interest(1, "golf");
Interest swimming = new Interest(3, "swimming");
Now lets assume we want two people called John and Mary. John likes golf and swimming while Mary only likes swimming. We'd then create their list of Interest as follows:
ArrayList<Interest> johnsInterests = new ArrayList<Interest>();
johnsInterests.add(golf);
johnsInterests.add(swimming);
ArrayList<Interest> marysInterests = new ArrayList<Interest>();
marysInterests.add(swimming);
And finally, we'd then create our two Person objects which will include the persons name and interests list.
Person john = new Person("John", johnsInterests);
Person mary = new Person("Mary", marysInterests);
And voila!
First, make an Interestclass:
public class Interest {
private int interestDangerRating;
private String interestName;
// .. getters and setters
}
then in the Personclass get rid of private String[] personInterests = new String[3];
and replace it by:
private ArrayList<Interest> interestsList = new ArrayList<>();
You're getting there with the logic of your Interests class, but it needs a few changes
import java.util.ArrayList;
import java.util.*;
public class Interests {
private int interestDangerRating;
// Is this a unique name for the entire class? If yes then no worries, but if not
// then its not needed, you've already got a list of interest names below
private String interestName;
// Change the array list to hold Strings, it's a list of words
private ArrayList<String> interestsList = new ArrayList<>();
public Interests (int interestDangerRating ,String interestName){
this.interestDangerRating = interestDangerRating;
this.interestName = interestName;
}
public void addInterest(String p){ // Again, change this to String
interestsList.add(p);
}
String getInterest(int i){ // Change this to return a String, since we changed the ArrayList above
return interestsList.get(i);
}
}
There's alot more you need to think about with this class too. How do you know how many interests are in the list, should there be a length variable? Or what about a method that returns the entire list of interests rather than just 1?
Also, there's only one interestDangerRating being set in this class; if each interest has a different danger rating, should't you be adding a danger rating for every interest?
In terms of accessing your new class, you'll need to create a class in your code by:
Interests variableName = new Interests(1, "football");
I have randomly chosen '1' and 'football' above, since they are in your Interest class' constructor. The way your class is built, you cannot use it without providing an int and a String when the object is made
Finally, to call methods on your class, you use the variable created above to call its methods:
variableName.addInterest("basketball");
String interest = variableName.getInterest(1);
If you're struggling, I recommend looking at a simple java tutorial online. instatiating java classes and calling their methods like this are fundamental concepts in Java :)
I have requirement to put "Name" and "phonenumber" in map.
I dont understand which thing I put as key and value in hashmap.
my requirement is we can and name with phone number and search with name.
like Name:"sanjay" phoneNumber:"111";
Name:"Krish" phoneNumber:"222";
later search it by name if I search 'sanjay' it provide me sanjay's phonenumber.
and, there is more then one user with same name and one user may have more then one phonenumber.
Thanks.
If you have a Person class, make a map like: Map<Person, Collection<String>>.
Then you can find phone numbers by doing map.get(somePerson), which returns null if the person doesn't exist.
You could also consider making a PhoneNumber class, which contains the string value of a validated phone number: Map<Person, Collection<PhoneNumber>>.
Use a class wrapper:
public class Person {
private List<String> phoneNumbers;
private String fullName;
//getters, setters, constructors for field values
#Override
public boolean equals(Object o) {
if (!(o instanceof Person) {
return false;
}
Person p = (Person) o;
return this.fullName.equals(p.fullName); //and other qualifying things
}
#Override
public int hashcode() {
//account for fields that you use in #equals(Object)
}
}
Then you can index based on whatever you want:
/* Full name => People */
Map<String, List<Person>> people = new HashMap<>();
/* Number => Person */
Map<String, Person> people = new HashMap<>();
Keep in mind, if you only compare the name in equals(Object), you're back to square one. Add more things to compare to be consistent with the uniqueness.
Hash maps great power is the ability to find the values in O(1) efficiency.
For this to work, the key must be the object you search by.
For example, if you want to search by name than your key should be the name.
And since a person can have several phone numbers, the value should be a List of phone numbers.
if you want to find the person name according to the phone number you should handle this the other way around - the key would be the phone number and the value would be the person name.
Perhaps you want both...
There are good answers above, may be this will also helps
Here Student made as key by overriding hashCode() and equals() method.
public class Student {
public String studentId;
public String studentName;
public Student(String studentId, String studentName) {
this.studentId=studentId;
this.studentName =studentName;
}
#Override
public int hashCode() {
return 1234;
}
#Override
public boolean equals(Object o) {
if (o instanceof Student) {
Student student=(Student)o;
if (this.studentId.equalsIgnoreCase(student.studentId)) {
return true;
} else {
return false;
}
} else {
return false;
}
}
}
Phone Number class :
public class PhoneNumber {
public String phoneNumber;
public PhoneNumber(String phoneNumber) {
this.phoneNumber =phoneNumber;
}
}
Person Class :
import java.util.HashMap;
import java.util.Set;
import java.util.List;
import com.google.common.collect.Lists;
public class Person {
public static void main(String[] args) {
Student e1=new Student("e001","studentOne");
Student e2=new Student("e002","studentTwo");
PhoneNumber d1 = new PhoneNumber("9999999998");
PhoneNumber d2 = new PhoneNumber("9999999999");
List listOfPhoneNumbersOfStudentOne = Lists.newArrayList(d1,d2);
PhoneNumber d3 = new PhoneNumber("9999999997");
PhoneNumber d4 = new PhoneNumber("9999999996");
List listOfPhoneNumbersOfStudentTwo = Lists.newArrayList(d3,d4);
/* Here Student made as key by overriding hashCode() and equals() method.*/
HashMap<Student, List<PhoneNumber>> map=new HashMap<Student, List<PhoneNumber>>();
map.put(e1, listOfPhoneNumbersOfStudentOne);
map.put(e2, listOfPhoneNumbersOfStudentTwo);
Set<Student> key=map.keySet();
for (Student student : key) {
System.out.println(student.studentId+" "+student.studentName +" ");
}
}
}
public class Assignment4 {
HashMap map = new HashMap<>();
public void addContact(String name, Integer number) {
map.put(name, number);
}
public void getphoneNumber(String name) {
if (map.containsKey(name)) {
Integer a = map.get(name);
System.out.println("Contact of " +name+" is " + a);
}
}
public static void main(String[] args) {
Assignment4 a4 = new Assignment4();
a4.addContact("vishal", 10345);
a4.addContact("sachin", 30456);
a4.addContact("sai", 30458);
Scanner s=new Scanner(System.in);
System.out.println("Enter name to get contact details");
a4.getphoneNumber(s.next());
s.close();
}
}
I have a Student class that contains an ArrayList of type Course, and Course is class with some fields like className, classTime, etc along with the appropriate getters and setters. Say I created an ArrayList of Course and have stored it into the Student class.
How can I for example print the className of a particular Course object (which is stored in an ArrayList stored in the Student class)?
So far I tried this, below is part of the code for class Student:
class Student {
ArrayList<Course> studentSchedule;
public ArrayList<Course> getStudentSchedule() {
return studentSchedule;
}
public void setStudentSchedule(ArrayList<Course> studentSchedule) {
this.studentSchedule = studentSchedule;
}
}
Then I have some code that created student1 of type Student and stored an ArrayList of Course into it.
Say I want to access the className in the first object in the ArrayList that's in student1. So far I have this and it works... is it fine?
ArrayList<Course> schedule = student1.getStudentSchedule();
System.out.print("\n course name at position 0 is " +
student1.getStudentScheduleClassName(0));
It feels weird to create another Arraylist just for this purpose... but then I thought since in line 1, schedule will only contain the addresses that point to the location and shouldn't take much space?
Is there a more appropriate way to do this?
Based on above discussion I tried to complete the solution for my reference.
import java.util.ArrayList;
import java.util.Iterator;
public class ListExample {
public static void main(String[] args) {
Student student1 = new Student();
ArrayList<Course> student1Schedule = new ArrayList<Course>();
student1Schedule.add(new Course("Computer Science", "Training Room"));
student1Schedule.add(new Course("Mobile App Development", "Training Room 2"));
student1.setStudentSchedule(student1Schedule);
// Prints only one course
System.out.println(" ** Course" + student1.getStudentSchedule().get(0).toString());
// Print all the courses attended by the student
ArrayList<Course> studentDetails = student1.getStudentSchedule();
Iterator<Course> studentIterator = studentDetails.iterator();
while (studentIterator.hasNext()) {
Course courseName = studentIterator.next();
System.out.println(courseName);
}
}
static class Student {
private ArrayList<Course> studentSchedule;
public ArrayList<Course> getStudentSchedule() {
return studentSchedule;
}
public void setStudentSchedule(ArrayList<Course> studentSchedule) {
this.studentSchedule = studentSchedule;
}
}
static class Course {
private String courseName;
private String className;
public Course (String courseName, String className){
this.className =className;
this.courseName = courseName;
}
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String toString (){
return "Course Name :" + this.courseName + "\n" + "Class Name : " + className + "\n";
}
}
}
public class Course{
private String className;
public String getClassName(){
return className;
}
public void setClassName(String c){
className =c;
}
}
So when you have this you can simply do
System.out.println(student1.getStudentSchedule().get(0).getClassName())
Make className into an instance variable of Course and have getter and setter methods within the Course for the class name. Then you will print out the class name.
You can access the first course's class name as:
System.out.print("\n course name at position 0 is " + schedule.get(0).getClassName());
since you've already defined getter/setter in the Course class as you mentioned.