Java Objects in Array List - java

i would like to run the update function automatically for every object i create. What do I have to change in my code, unfortunately it doesn't work
How can I initialize an object in my ArrayList?
:(
Creating an Arraylist and initialize with name
public class Main {
public static void main(String... args) {
Zuhoerer Maria = new Zuhoerer("Maria");
Zuhoerer Sepp = new Zuhoerer("Sepp");
Zeitansager.sagAn();
}
}
class Zuhoerer {
private String name;
private String Ansager;
Zuhoerer(String name) {
this.name = name;
}
private void setAnsager(String datumstring) {
Ansager = datumstring;
}
void update() {
setAnsager(Zeitansager.getZeit());
Zeitansager.schreibeEin(name);
System.out.println(name + " hat gerade die die Zeitansage gehört:
[Datum/Uhrzeit]: " + Ansager);
Zeitansager.trageAus(name);
}
}
class Zeitansager {
private static String datumString;
private static ArrayList<String> abonnenten;
Zeitansager(String datumString) {
Zeitansager.datumString = datumString;
abonnenten = new ArrayList<>();
}
static void schreibeEin(String name) {
abonnenten.add(name);
}
static void trageAus(String name) {
abonnenten.remove(name);
}
static void sagAn() {
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.YYYY' 'HH:mm:ss");
String datum = sdf.format(new Date());
datumString = datum;
for (int i=1; i <= abonnenten.size(); i++) {
abonnenten.update();
}
}
static String getZeit() {
return datumString;
}
}
update function is not called

Your ArrayList in Zeitansager have to be of type Zuhoerer rather than String.
Then in your loop in sagAn() you need to invoke:
abonnenten.get(i).update();
instead of:
abonnenten.update();
Finally your method static void schreibeEin(String name), should actually take a Zuhoerer as an argument.

To run "update" function every time you create an object you must put a call to this function inside your constructor. Like this:
Zuhoerer(String name) {
this.name = name;
update();
}
What are you trying to do with your arraylist? Give me more details so I can try to help you.

Related

Static Method addStudents

So I need help with this part of JAVA in my COP class OOP programming.
First is that I need to change the addStudent to static method but the code will not run because the this.student is not static which makes no sense because it already private static
import java.util.Arrays;
public class InitializerDemo {
public static final int MAX_STUDENTS = 10;
private static Student[] students;
private Instructor instructor;
private static int numStudents = 0;
// default constructor
public InitializerDemo() {
}
// instructor mutator
public void setInstructor(Instructor instructor) {
this.instructor = instructor;
}
// add a student, increment the count
//This PART!!! HELP
public static void addStudent(Student s) {
this.students[numStudents++] = s;
}
public static void main(String[] args) {
// create our aggregator object
InitializerDemo id = new InitializerDemo();
// set the instructor
id.setInstructor(new Instructor("Sally"));
// add the students
id.addStudent(new Student("Sam"));
id.addStudent(new Student("Rajiv"));
id.addStudent(new Student("Jennifer"));
id.addStudent(new Student("Test Student"));
// output
System.out.println(id);
}
public String toString() {
String s = "Instructor = " + instructor + "\n" +
"Number of students = " + numStudents + "\n" +
"Students: " + Arrays.toString(students) + "\n";
return s;
}
}
class Student {
private String name;
// instance initializer block
{
name = "noname";
}
public Student() {
}
public Student(String name) {
this.name = name;
}
public String toString() { return name; }
}
class Instructor {
private String name;
// instance initializer block
{
name = "noname";
}
public Instructor() {
}
public Instructor(String name) {
this.name = name;
}
public String toString() { return name; }
}
I need help with that addStudent Method
These are the instructions and sorry to confuse all you guys and thank you for putting time to help me
change the instance variables representing the number of students and the Student array in the aggregator object to private static variables.
• change the addStudent method in the aggregator object from an instance method to a static method
• Remove all initialization/instantiation operations from the aggregator object’s default constructor; the constructor can simple be an empty method { }
• provide a static initializer block in the aggregator object which does the following:
o initializes the number of students to 0
o instantiates the student array
o adds a single student named “Test Student” to the array using the addStudent method
Change
this.students[numStudents++] = s;
to
students[numStudents++] = s;.
I believe that should work.
You also have to initialize the students, so change
private static Student[] students;
to
private static Student[] students = new Student[MAX_STUDENTS];

How can I add mulitple items to an ArrayList without using Arrays

I'm learning Java and trying out stuff. I want to be able to print students' names with their courses and grades. I have written the following classes to achieve that but since I'm a newbie, I'm wondering if I have done it correctly. The code does display what I want but how can I best optimize it?
Subject class:
public class Subject {
private String subjName;
private int subjGrade;
public Subject(String subjName, int subjGrade) {
this.subjName = subjName;
this.subjGrade = subjGrade;
}
public void setName(String name) {
this.subjName = name;
}
public String getName() {
return subjName;
}
public int getGrade(){
return subjGrade;
}
#Override
public String toString() {
return String.format( getName() + ", Grade:" + getGrade());
}
}
StudentSubJGrade class:
import javax.swing.text.html.HTMLDocument;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
public class StudentSubJGrade {
String name;
Subject[] subjects;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setSubjects(Subject[] subjects) {
this.subjects = subjects;
}
public StudentSubJGrade(String name, Subject[] subjects) {
this.name = name;
this.subjects = subjects;
}
#Override
public String toString() {
return String.format("Name:" + getName() + " Subjects:" + Arrays.toString(subjects));
}
}
I feel I can add the subjects via the ArrayList but couldn't come up with how to do it after hours of trials. How can this be done without using arrays as I have done?
Driver class:
import java.util.ArrayList;
public class StudentSubjGradeDriver {
public static void main(String[] args) {
ArrayList<StudentSubJGrade> test = new ArrayList<>();
ArrayList<StudentSubJGrade> test2 = new ArrayList<>();
Subject[] subjects = new Subject[3];
subjects[0] = new Subject("Maths",80);
subjects[1] = new Subject("Physic",90);
subjects[2] = new Subject("Chemistry",70);
Subject[] subjects1 = new Subject[4];
subjects1[0] = new Subject("Maths",80);
subjects1[1] = new Subject("Physic",90);
subjects1[2] = new Subject("Chemistry",70);
subjects1[3] = new Subject("Geography",90);
test.add(new StudentSubJGrade("Anita",subjects));
test2.add(new StudentSubJGrade("James",subjects1));
System.out.println(test);
System.out.println(test2);
}
}
After carrying out suggestions, I tried improving on the code by creating the subjects as ArrayLists but I'm having trouble with it:
ArrayList<Subject> subjects;
public StudentSubJGrade(String name, ArrayList<Subject> subjects) {
this.name = name;
this.subjects = subjects;
}
Now in the main method, I tried the following but I'm getting an error:
ArrayList<StudentSubJGrade> test = new ArrayList<>();
ArrayList<Subject> st = new ArrayList<>();
st.add(new Subject("Maths",90));
test.add("Anita",st);
The problems with your code are that a) you are passing an array to the constructor without copying it, and b) you cannot change the subjects later.
For example, for a) say that you do the following:
Subject[] subjects = new Subject[] {
new Subject("Maths",80),
new Subject("Physic",90),
new Subject("Chemistry",70),
new Subject("Geography",90)
};
StudentSubJGrade student = new StudentSubJGrade("Hassan", subjects );
So far, so good. But now:
subjects[ 0 ] = null;
And suddenly your StudentSubJGrade student object has a null in its subjects.
This effect has to do with arrays being objects (like Student), instead of value types (as in int x = 5), which implies that in your case both references will point to the same array.
Take look here for a demo on shared array objects.
You can avoid this by changing the method setSubjects().
public void setSubjects(Subject[] subjects)
{
this.copySubjects( subjects );
}
private void copySubjects(Subject[] subjects)
{
final int arraySize = subjects.length;
this.subjects = new Subject[ arraySize ];
System.arraycopy( subjects, 0, this.subjects, 0, arraySize );
}
public StudentSubJGrade(String name, Subject[] subjects) {
this.name = name;
this.copySubjects( subjects );
}
If you need to change the subjects later, then you need to change the array inside the class for an ArrayList, and never expose it. You can get the subjects with the toArray() method, and accept an array or an enumeration to load it.
public void clearSubjects()
{
this.subjects.clear();
}
public void addSubjects(Subject[] subjects)
{
this.appendSubjects( subjects );
}
private void appendSubjects(Subject[] subjects)
{
this.subjects.addAll( subjects );
}
public Subject[] getSubjects()
{
return this.subjects.toArray( new Subject[ 0 ] );
}
public StudentSubJGrade(String name, Subject[] subjects)
{
this.name = name;
this.appendSubjects( subjects );
}
private ArrayList<Subject> subjects;
Hope this helps.
You have to use arrays because the StudentSubJGrade constructor expects the second argument to be a Subject[]. However, you can simplify your creation of the arrays:
import java.util.ArrayList;
public class StudentSubjGradeDriver {
public static void main(String[] args) {
ArrayList<StudentSubJGrade> test = new ArrayList<>();
ArrayList<StudentSubJGrade> test2 = new ArrayList<>();
Subject[] subjects = new Subject[] {
new Subject("Maths",80),
new Subject("Physic",90),
new Subject("Chemistry",70)
};
Subject[] subjects1 = new Subject[] {
new Subject("Maths",80),
new Subject("Physic",90),
new Subject("Chemistry",70),
new Subject("Geography",90)
};
test.add(new StudentSubJGrade("Hassan",subjects));
test2.add(new StudentSubJGrade("James",subjects1));
System.out.println(test);
System.out.println(test2);
}
}

Java programming error Pass by reference

I have an java application where a object reference "Validate.Options" is passed as parameter to the function "ValidateResult(Validate.Options option)" and the function is called iterative. Within this function based on the certain condition the property "enableProcessing" of the passed object gets changed which does not get reset on the next iterate. How can I reset this property?
Below is the sample code.
public interface Validate
{
public List validate();
public class Options implements Serializable
{
public String name;
public boolean enableProcessing = true;
public Options(String name)
{
this.name = name;
}
}
}
public class Coder
{
public String name;
public int age;
public Coder(String name, int age)
{
this.name = name;
this.age = age;
}
public void ValidateResult(Validate.Options option)
{
if(option.name.equals(this.name) && option.enableProcessing)
{
option.enableProcessing = false;
//
//business logic and function call
//
}
}
public static void main(String[] args)
{
Validate.Options options = new Validate.Options("Test");
List<Coder> coders = new ArrayList<Coder>();
Coder coder = new Coder("Test", 28);
Coder coder1 = new Coder("XYZ", 18);
Coder coder2 = new Coder("Test", 16);
coders.add(coder);
coders.add(coder1);
coders.add(coder2);
for(Coder co : coders)
{
co.ValidateResult(options);
}
}
}
If I understood the question well - in your for loop, simply add a line of code to reset the value of your public Validate.Options.enableProcessing field
for(Coder co : coders)
{
//reset options object for the next iteration
options.enableProcessing = true;
co.ValidateResult(options);
}
Make options immutable if you do not want it to be changed:
public class Options implements Serializable
{
public final String name; // final prevents changes
public final boolean enableProcessing = true; // final prevents changes
public Options(String name)
{
this.name = name;
}
}
To locally work with enableProcessing copy its value to a local variable.
public void ValidateResult(Validate.Options option)
{
boolean enableProcessing = option.enableProcessing; // create local copy
if(option.name.equals(this.name) && enableProcessing) // use local copy
{
enableProcessing = false; // only change local copy
//
//business logic and function call
//
}
}
Alternatively create new, fresh Options for each loop:
public static void main(String[] args)
{
List<Coder> coders = Arrays. asList(
new Coder("Test", 28),
new Coder("XYZ", 18),
new Coder("Test", 16)
);
for(Coder co : coders)
{
Validate.Options options = new Validate.Options("Test"); // fresh options for each iteration
co.ValidateResult(options);
}
}

(identifier expected) getter/setter and objects

I've got a problem with my programm. When i try to compile following i just receive the message:
Tutorium.java:15: error: <identifier> expected
public void settName(vorlesung.lectureName) {
^
So my Code:
Tutorium.java
public class Tutorium {
private Vorlesung vorlesung;
public String tName;
private int tNumber;
public int gettNumber() {
return this.tNumber;
}
public String gettName() {
return this.tName;
}
public void settName(vorlesung.lectureName) {
this.tName = vorlesung.lectureName;
}
public String toString() {
return (this.tName + ", " + this.tNumber);
}
public Tutorium(int tNumber){
this.tNumber = tNumber; } }
Vorlesung.java
public class Vorlesung {
public String lectureName;
private int lectureNumber;
private int lecture;
private Dozent dozent;
private String lecturerlName;
public String getlectureName(){
return this.lectureName;
}
public int lectureNumber(){
return this.lectureNumber;
}
public int lecture(){
return this.lecture;
}
public String getlecturer(){
this.lecturerlName = dozent.lecturerlName;
return this.lecturerlName;
}
public String toString() {
return (this.lectureName + ", " + this.lectureNumber);
}
public Vorlesung(String lectureName, int lecture) {
this.lectureName = lectureName;
this.lecture = lecture +1;
this.lectureNumber = this.lecture -1;
this.lecturerlName = lecturerlName;
}}
My Main-Method:
public class MainVorlesung {
public static void main(String[] args) {
Student student = new Student("STUDENTNAME", "STUDENTLASTNAME", 178, 1);
Vorlesung vorlesung = new Vorlesung("Programmieren", 13341);
Tutorium tutorium = new Tutorium(3);
Dozent dozent = new Dozent("LECTURERFIRSTNAME", "LECTURERLASTNAME", 815);
System.out.println(student.toString());
System.out.println(vorlesung.toString());
System.out.println(tutorium.toString());
System.out.println(dozent.toString());
}}
My goal is to set the value of tName equal the value of vorlesung.lectureName.
Why can't i do this that way?
I appreciate every help. :)
Thanks
For methods, the arguments that you pass in must have a declared value.
In this case, a String. So you need to change your method to this:
public void settName(String newLectureName) {
this.tName = newLectureName;
}
Read more about what a java method is and how to create one here: http://www.tutorialspoint.com/java/java_methods.htm
Change settName to
public void settName(String name) {
this.tName = name;
}
Since your goal is:
My goal is to set the value of tName equal the value of vorlesung.lectureName.
You should get rid of the setName method entirely since it will depend entirely on the vorlesung field and so should not be changeable. You should also get rid of the tName field, and instead change getName() to:
public class Tutorium {
private Vorlesung vorlesung;
// public String tName; // get rid of
private int tNumber;
public String gettName() {
if (vorlesung != null) {
return vorlesung.getlecturer();
}
return null; // or throw exception
}
// *** get rid of this since you won't be setting names
// public void settName(Vorlesung vorlesung) {
// this.tName = vorlesung.lectureName;
// }
I have just now noticed that your Tutorium class does not have and absolutely needs a setVorlesung(...) method.
public void setVorlesung(Vorlesung vorlesung) {
this.vorlesung = vorlesung;
}

HashMap find() with arrays

I have a class named Machine defined as :
class Machine
{
private String name;
Machine() { name = null; }
// set , get methods of String name
}
I also have a class named MachineAtt implementing an interface Att like:
// Att interface
interface Att
{
void add(Machine obj);
Machine find(String name)
}
// MachineAtt class
class MachineAtt implements Att
{
protected Map<String,Machine> hashTable = new HashMap<String,Machine>();
// ovveride methods from interface Att
}
the main function is:
Machine car = new Machine();
car.setName("MB");
//create an object of MachineAtt
MachineAtt foundit = new MachineAtt();
foundit.add(car);
foundit.find("MB");
My question is: how can I do the same but with an array?
for example, I want to foundit.add(someArray) and then I search certain item in this array by using method find(); I hope you get what I mean. Any ideas?
Your addAll(Machine[] machines) method is like this.
void addAll(Machine[] machines){
for(Machine m:machines){
add(m);
}
}
Your findAll(String[] names) method is like this.
Machine[] findAll(String[] names){
ArrayList<Machine> machines =new ArrayList<ArrayList>();
for(String s:names){
Machine m = find(s);
if(m!=null){
machines.add(m);
}
}
return machines.toArray(new Machine[0])
}
You could create a method like
void addAll(Machine[] machines)
and in its implementation, you add all elements from this array into the hashtable.
add methods
void add(Machine[] arr);
Machine[] find(String[] names);
and implement them in your class
Since you asked to this with an array i have tried it with the arrays. But I would rather suggest to go with an ArrayList as it is dynamic and insertion and searching is also fast and easy. Never mind try the following snippet.
class Machine
{
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
Machine() { name = null; }
}
interface Att
{
void add(Machine obj);
Machine find(String name);
}
//MachineAtt class
class MachineAtt implements Att
{
protected Machine[] arr = new Machine[10];
#Override
public void add(Machine obj) {
for(int i = 0; i<arr.length;i++ )
{
if(arr[i]==null)
arr[i] = obj;
}
}
#Override
public Machine find(String name) {
Machine mac = null;
for(int i = 0;i<arr.length;i++)
{
if(arr[i].getName().equals(name))
mac = arr[i];
}
return mac;
}
}
public class TEst {
public static void main(String[] args) {
Machine car = new Machine();
car.setName("MB");
//create an object of MachineAtt
MachineAtt foundit = new MachineAtt();
foundit.add(car);
foundit.find("MB");
}
}

Categories

Resources