I am trying to make a method that will create a new unique object based on another class that I have have in the same project. I know that the last line wont compile, but is there a way to accomplish the same goal?
Ideally if the fName=John and lName=Smith, then the new "Employee" object created on the last line would be called "JohnSmith" but the goal is just to create a unique instance of the object every time that the method is called
public static void createEmployee(int number){
Scanner input= new Scanner(System.in);
System.out.printf("Enter first name for employee %s: ",number);
String fName=input.next();
System.out.printf("Enter last name for employee %s: ",number);
String lName=input.next();
Employee fName+lName= new Employee(fName,lName);
}
I am fairly new to Java, and object oriented programming in general so if I am going about this wrong I am open to going about it a different way.
No, what you're describing isn't possible.
As a conceptual exercise, your variables should describe the kind of data they're holding. It may sound pretty plain, but employee would be a better name for that variable than JohnSmith or SteveJobs or any other first + last name combination.
If you're intending to create a new instance of an Employee every time, you should return the Employee instance from the method instead of declaring it void. Then you can use it however you like wherever you call it.
public static Employee createEmployee(int number){
Scanner input = new Scanner(System.in);
System.out.printf("Enter full name of employee %d, separated by spaces: ", number);
String fName = input.next();
String lName = input.next();
return new Employee(fName, lName);
}
You can't do it that way. But remember, many "JohnSmith" exist - you would run into homonyms easily.
If these aren't a problem, you could use a Map to bind a key (The String made with Surname + Name) to a value (your employee).
Good luck and welcome to StackOverflow!
UPDATE
If homonyms are a problem, you will need to use unique IDs; they assure you that you have no overlaps. You could build an ID in the Employee itself, and put them in a List, or you can put them in an Array - the ID will then be their position in the array.
No. You can't combine a variable like that, but you could say something like
// Employee fName+lName= new Employee(fName,lName);
Employee employee = new Employee(fName, lName);
And if Employee overrides toString() then
System.out.println(employee);
should give you the output you would expect.
I second the hashmap. Having a human readable variable name dynamically created is overly complicated. Using a hashmap you can reference the object with a string
HashMap<String, Employee> employees = new HashMap<String, Employee>();
employees.put(fName + lName, new Employee(fName, lName));
To get the employ obj
employees.get(fName + lName);
Related
Okay, so I'm in java Object Oriented Programming and I'm stuck on one little thing on a project.
I have to create a class that holds a student name, calculates the total score and calculates the average score. But what's holding me up is that I need to create an object, that is called by the name that is given to me from input from the scanner.
I also am not 100% sure how to get the information from the program to the class, I think I just put them in the variable name from the name, but if I'm wrong, please tell me.
What I have so far is:
public class Prog2 {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
Student name = new Student();
System.out.println("Please enter the name of the student.");
String theName = input.nextLine();
name.setName(theName);
System.out.println();
System.out.printf("Name of the object is", name.getName());
}
}
Right now I want to see I I can get the name in there. I also need to name the project the same name as the name that's given to me.
It's not very clear what you are asking, you are asking how to create a student object and set that objects name field to the input given from the scanner?
One way to pass information from the program to the class is to create a constructor that sets the fields value upon object creation:
Student thisStudentObject = new Student(inputName, inputGrade)
Of course this is dependant upon the Student class having a contructor that matches those data types (in that order). for more information on constructors, see https://stackoverflow.com/a/19941847/4064652
I am attempting to make a course registration system and one of my classes (Course) is centered around course attributes (ie. Course number, course name, instructors, students). I am making an ArrayList so that the Administrator (one of the user types) may add as many instructors to the course as he/she would like- I have created a Scanner and a String variable and everything, but when I write the .add command, Eclipse highlights ".add" and says "the method .add() is undefined for the type of scanner". Now, I can understand this, but I have no idea how to fix it and I've tried so many ideas.
Here is the method:`
public static String Instructor(){
String courseInstructors;
System.out.println("Please add name(s) of course instructors.");
ArrayList<String> Instructors= new ArrayList<String>();
Scanner courseInst = new Scanner(System.in);
courseInstructors = courseInst.next();
//courseInst.add(courseInstructors);
for(String courseInstructors1 : Instructors) {
courseInstructors1 = courseInstructors;
courseInst.add(courseInstructors1);
}
return;
}`
Please adhere to Java naming conventions ad use lower case for variable names - instructors instead of Instructors.
Also, you want to add to your arraylist, so call add() on
instructors.add(courseInstructors1)
You may also want to consider choosing better variable naming than courseInstructors1, for instance just courseInstructor, since you are referring to on instructor of all instructors.
Also in your for loop you are doing the following
for(String courseInstructors1 : Instructors) {
courseInstructors1 = courseInstructors;
courseInst.add(courseInstructors1);
}
This can be simplified to
for(String courseInstructors1 : Instructors) {
courseInst.add(courseInstructors);
}
And if you look at the simplification you will see that iterating through Instructors make no sense here, since you are not using the contents of courseInstructors1.
I'm trying to understand what your loop is for.
if you are trying to get multiple instructor names from one input then you need something like this.
//get input
//"John Peggy Adam blah blah"
courseInstructors = courseInst.next();
//split the string by white space
String[] instArr = courseInstructors.split(" ");
//will give array of John, Peggy, Adam, blah, blah
Then do your foreach loop to add them to the list.
for(String inst: instArr){
instructors.add(inst);
}
Otherwise I would suggest doing something like this so you don't have to worry about splitting names and such.
courseInstructor = courseInst.nextLine();
while(!courseInstructor.equals("done"){
//add name to list of instructors.
instructors.add(courseInstructor);
//get next name.
courseInstructor = courseInt.nextLin();
//if the user types done, it will break the loop.
//otherwise come back around and add it and get next input.
}
so I have a program that ask(input) for stuff(variable int string etc..)and those elements are after that passed to the constructor.However, each time I input new values,previous are overwritten.How do I make it create a new one instead of overwritting the previous values?I am very new to Java and im kinda confuse.Heres my code:
Scanner scan1 = new Scanner(System.in); //user input the name
System.out.print("name: \n");
String name = scan1.nextLine();
and then pass it to the constructor:
Balloon aballoon = new Balloon(name);
my constructor looks like
public Balloon(String name){
setName(name);
and the method of it
public String thename
public void setName(String name){
if(name.matches("[a-zA-Z]+$")){
thename = name;
}
So yeah im wondering how to build multiple object(character) whitout overwritting the previous one,and how to store them(the character).
thank you
You can use an ArrayList<Balloon> to store multiple Balloon objects:
ArrayList<Balloon> baloons = new ArrayList<Balloon>;
//Read name
baloons.add(new Balloon(name));
//baloons now contains the baloon with the name name
For more information on how to use the ArrayList class, see Class ArrayList<E>.
I'd use a loop akin to something like the following to store all the balloons that the user wants:
List<Balloon> balloonList = new ArrayList<>();
Scanner input = new Scanner(System.in);
String prompt="Name?(Enter 'done' to finish inputting names)";
System.out.println(prompt); //print the prompt
String userInput=input.nextLine(); //get user input
while(!userInput.equals("done")){ //as long as user input is not
//"done", adds a new balloon
//with name specified by user
balloonList.add(new Balloon(userInput));
System.out.println(prompt); //prompt user for more input
userInput=input.nextLine(); //get input
}
For modify, I'm going to assume that you wish to find the balloon using its name(IE: If someone wants to delete/modify the balloon with the name "bob", it will delete/modify the (first) balloon in the ArrayList that has the name "bob".
For deletion, it is simple- write a a simple method to find the balloon specified(if it is in the list) and delete it.
public static boolean removeFirst(List<Balloon> balloons, String balloonName){
for(int index=0;index<balloons.size();index++){//go through every balloon
if(balloons.get(index).theName.equals(balloonName){//if this is the ballon you are looking for
balloons.remove(index);//remove it
return true;//line z
}
}
return false;
}
This method will look for the Balloon specified by name and remove the first instance of it, returning true if it actually found and removed the balloon, otherwise removing it. If you wish to remove all balloons by that name, you can create a boolean b at the beginning of the method and set it to false. Then, you can change line z to
b=true;
and then at the bottom of the method, return b.
Now, by edit, you could mean one of two things. If you're planning on modifying the actual name of the balloon, you can use a loop like the one I made above and just modify the name when you find it, again you can make it modify all balloons with that name, or just the first one you find.
Or, if by modify a balloon you mean to replace the balloon in the ArrayList with a new balloon that has a different name, you will want to use the following methods:
balloons.remove(i);//remove balloon at index
balloons.add(i,newBalloon);//put the new balloon(with different data) at the index of the old one
This question already has answers here:
Assigning variables with dynamic names in Java
(7 answers)
Closed 9 years ago.
I want to create new object and to give it user input name.
Example user input "robert" wil match to:
Action robert = new Action();
robert.eat();
What do I need to change in the program so I can create a new object with a dynamic name?
Many Thanks.
I write the next code:
import java.util.Scanner;
public class Human {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner user_input = new Scanner( System.in );
String first_name;
System.out.print("Enter your first name: ");
first_name = user_input.next( );//robert
System.out.println("You are " + first_name);//robert
Action first_name = new Action();
Food orange = new Food();
robert.eat(orange);
}
}
Java, unlike other languages, does not have a way to dynamically create variable names. Variable names are declared in the code. In order to achieve what you're trying to do, look into the Collection's Map interface. This will allow you to "map" a user given name to some value.
Quick example:
//1) Setup the mapping,
//The first parameter to put() is the key (perhaps a user given name?)
//and the second parameter is actual value you want to map for that key.
//note that although I'm using a String as the key and a String as the value
//You can use pretty much any object as the value. Keys are recommended to be
//immutable objects (a String is a good one)
Map<String,String> mMap = new HashMap<String,String>();
mMap.put("John", "Orange");
mMap.put("Steve","Apple");
//2) Once the map is setup, you can then retrieve values given a key:
System.out.println("John's fruit is: "+mMap.get("John"));
More info here.
This is not possible. How can you declare the name of the Class object as a variable.
Variable names cant be specified(created) at run time(dynamically).
Hi everyone once again thanks for taking the time to look at my issue.
I am trying to create a program that keeps track of employees and the diffrent departments that they are working in.
The program first reads from a text file all the initial data to get the program going. The program then has a while loop within a while loop. The first loop will read the department details and then create the department
in then the next (inner) while loop it reads all the employees accosiated with this department,It then after reading the details of the employee creates the employee and adds it to the previously created department to say this is the department I work in.
after adding all the employees to the department, it then exits that inner loop and sends the department with the employees inside it to the mainDriver for storage. It does this for the remaining departments again adding their associated employees and so on.
The problem Is: it seems to create each department okay and add it to the mainDriver, but all the employees are added to the first department and the remaining department are left empty. Which is not the way it should work as their are several employees in each department.
Why is it not moving on to the next department as the new Department is instantiated??
Could I please have some help to see where I may be going wrong.
this is the code that read in the data.
while (index < numberOfDepartmentsToRead )
{
String depName1 = inFile.nextLine();
String location1 = inFile.nextLine();
String numberOfEmps = inFile.nextLine();
int numberOfEmps1 = Integer.parseInt(numberOfEmps);
Department newDepartment = new Department(depName1 , location1);
while (i < numberOfEmps1 )
{
String fName = inFile.nextLine();
String lName = inFile.nextLine();
String gender = inFile.nextLine();
String address = inFile.nextLine();
String payLevel = inFile.nextLine();
int dPayLevel = Integer.parseInt(payLevel);
Employee employeesFromList = new Employee(randomIDno, fName, lName, gender, dPayLevel);
newDepartment.setAddEmp(employeesFromList, randomIDno);
i++;
}
i = 0;
index++;
MainDriver.setDepartmentToSystem(newDepartment);
}
the employee is passed to this method in the departments class
public static void setAddEmp(Employee theEmp, int idNumber)
{
employeesInThisDepartment.add(theEmp);
employeeMap.put(idNumber, theEmp);
}
the department is added to the mainDriver classes storage method which is this
public static void setDepartmentToSystem(Department theDepartment)
{
allDepartments.add(theDepartment);
}
public static void setAddEmp(Employee theEmp, int idNumber)
Why is it static? Make it instance method.
Make employeesInThisDepartment instance variable instead of static.
You might want to check your use of static. It is difficult to know without seeing all your code but I wonder if setAddEmp should not be a static method.
Your employeesInThisDepartment is a static variable, whereas you need one per-Department.
Each Department should have its own instance, with an employees property, to which the department's employees are added. Similarly, the method to add an employee to the department should be an instance method, not static.
Binyomin, i think your inner while controller makes wrong...
while (i < numberOfEmps1 ){ i++; }
I think this loop will traverse all the employees in the file. Then the next iteration of the inner loop will return EOF...
Try posting your file structure..