Avoid overwritting constructor content - java

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

Related

How to get the name of an object to call a class method if I don't know the name?

I have a class called AttendanceSystem:
LinkedList<LinkedList<String>> student = new LinkedList<LinkedList<String>>();
public AttendanceSystem(String s){
student.add(new LinkedList<String>());
student.get(student.size()-1).add(s);
}
public void setEmail(String d){
student.get(student.size()-1).add(d);
}
In my main I have this:
System.out.println("Please enter your ID.");
String s = keyboard.nextLine();
new AttendanceSystem(s);
System.out.println("Please enter your Email.");
String d = keyboard.nextLine();
I want to add more elements into the object but since I used new AttendanceSystem(s) I don't know the name of the object I created so I cannot simply do objectname.setEmail(s). How can I call a method to that very object? Or is there a better way to do this?
I am using a scanner so I can keep adding new objects automatically until I tell it to stop.
UPDATED:
My main now:
LinkedList<AttendanceSystem> list = new LinkedList<AttendanceSystem>();
System.out.println("Please enter your ID.");
String s = keyboard.nextLine();
list.add(new AttendanceSystem(s));
System.out.println("Please enter your Email.");
String d = keyboard.nextLine();
list.get(list.size()-1).setEmail(d);
I stored all the objects in a linked list so I can just do this list.get(list.size()-1).setEmail(d);.
Simply:
AttendanceSystem identiferName = new AttendanceSystem(s);
then use the setEmail to set the relevant data for that object.
EDIT
you might want to create an addAttendee method which will take the ID and Email then simply add it to the LinkedList inside the AttendanceSystem class.
public void addAttendee(String id, String email){
LinkedList<String> myList = new LinkedList<>();
myList.add(id);
myList.add(email);
this.student.add(myList);
}
note - in this case, you should just get rid of the constructor parameter & don't use it to add any IDs or Emails.
With does changes in mind and considering that you don't want to store a reference to a new object, you call it like this:
new AttendanceSystem().addAttendee(id,email);

Using an array to store multiple variables from user input

I am relatively new to Java and would like to know how to store variables separately from a single line of user input.
At the minute the user is prompted to enter football results in the following format
home_name : away_name : home_score : away_score
and I am using a while loop to continue to ask user for input until they enter "stop"
(while (input != "stop))
Once the loop is broken I would like my program to output a variety of data such as total games played, but I'm struggling to store the home_name, away_name etc.. especially if the user wishes to enter multiple lines of results.
Two mainstream ways to store a "record" are:
Maps
Data objects
A map is more generic:
Map<String,String> match = new HashMap<>();
match.put("home_name", "Alvechurch Villa");
match.put("away_name", "Leamington");
match.put("home_score", "0");
match.put("away_score", "6");
You can add a map to a list:
List<Map<String,String>> matches = new ArrayList<>();
matches.add(list);
... and retrieve them:
Map<String,String> match = matches.get(0);
System.out.println(match.get("away_score"));
A data object is more tuned to your data format, but you have to write the class yourself.
public class Match {
public String homeName;
public String awayName;
public int homeScore;
public int awayScore;
}
Now you can use this class:
Match match = new Match();
match.homeName = "Studley";
// etc.
You can add and retrieve these from lists too:
List<Match> matches = new ArrayList<>();
matches.add(match);
Match aMatch = matches.get(0);
This is simple, but it's considered bad practice to have public fields like this - it's better to get at them via methods. For brevity, here's a data class with only one field:
public class Player {
private String name;
public Player(String name) {
this.name = name;
}
public String name() {
return name;
}
}
Player neilStacey = new Player("Neil Stacey");
You can use the same technique with all the fields in Match.
(A common style is to name a method like this getName(), and also to have a setName(). I have used a different style and made the object immutable, in an effort to set a good example!)
One advantage of the data object is that it has different types for different fields: homeName is a String, homeScore is an integer. All the fields in the Map are Strings. You can get around this by using Map<String,Object> but then as a consumer you have to cast to the right type when you read.
String homeName = (String) match.get("home_name");
Data objects allow the compiler to do a lot of compile-time checking that helps you know your code is correct. If you use a map, you won't find out until runtime.
Prompt the user separately for each input.
System.out.println("home_name: ");
String hN = scan.next();
System.out.println("away_name: ");
String aN = scan.next();
System.out.println("home_score: ");
String hS = scan.next();
System.out.println("away_score: ");
String aS = scan.next();

Java Programming Making Classes Object names

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

Can you create a unique variable name by concatenating two other variables?

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);

How do I add a User Input of type String to an ArrayList in Java?

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.
}

Categories

Resources