How can I implement Random in java - java

Well, I need to implement two classes Student and School. Each student has an Id number consisting of number of arrival and the dormitory number, the second one should be random number from an array of elements.
Then I need to register these students to appropriate schools, there are four of them. This registration have to be random also. so I have Student and Schools classes here,
public class Student {
private String name;
private int id, size;
private int dorm;
/**
* Constructor of a class Student
*
* #param n sets the name of the student
*/
public Student(String n) {
name = n;
int d[] = {11, 19, 20, 22, 23, 24, 38, 39};
Random r = new Random();
dorm = d[r.nextInt(d.length)];
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the dorm
*/
public int getDorm() {
return dorm;
}
/**
* the id to set
*/
public void setId() {
id = size;
id = id*100 + dorm;
}
/**
* #return the id
*/
public int getId() {
return id;
}
#Override
public String toString() {
String result = "The student " + name + " has an id " + id + ". Located in the dormitory #" + dorm + ".";
return result;
}
And School class here,
import adt.Queue;
public class School {
private int size;
private String name;
private Queue q = new LinkedListQueue();
public School(String n) {
name = n;
size = 0;
}
public void register(Student st) {
q.enqueue(st);
size++;
}
public int getSize() {
return size;
}
public void viewStudents() {
System.out.println(q.toString());
}
#Override
public String toString() {
String str = "The School of " + name + ". The number of students is " + size + ".";
return str;
}
So as you can see, I have register method in the School class which register new Student to a specific school.
So my problem is that how can I get data size from a School class to use it in the Student class ???
I am only a student don't judge me please ^^)

When you add a student to the school, you should also tell the student what school they're in.
Add a field and a method to Student
public class Student {
private String name;
private int id, size;
private int dorm;
private School school;
public void setSchool( School school ) {
this.school = school;
}
Then add the code in School to tell the student.
public void register(Student st) {
q.enqueue(st);
size++;
st.setSchool( this );
}
Now as long as school is not null in Student, a student can find the size of their school.

If I understand your problem correctly, what you need is to add an int parameter to your student's setId() method:
public void setId(int id) {
this.id = id * 100 + dorm;
}
and then on the register() method you would do:
public void register(Student st) {
q.enqueue(st);
st.setId(size++);
}
I hope that helps you, good luck!

Related

How do I print out an array list containing both the name of a student and the id of a student?

public class pro1{
static ArrayList <String> student = new ArrayList<String>();
static ArrayList <Integer> id = new ArrayList<Integer>();
String name;
int ID;
public pro1() {
this.name = "";
this.ID = 0;
}
public pro1(String name, int ID) {
this.name = name;
this.ID = ID;
}
public boolean addStudent(String name, int ID) {
student.add(name);
id.add(ID);
return true;
}
/*#Override
public String toString() {
return name + ID;
}*/
public static void main(String args[]) {
pro1 stu = new pro1();
stu.addStudent("john", 1);
stu.addStudent("johnny", 2);
System.out.println(stu);
}
}
I want to print out both the name of the student and the student id using ArrayList. however, I'm not sure how to do that since in this class I can only print out the ArrayList of names or the ArrayList of id. I'm thinking of maybe using another class to create a student object, but I'm not sure how to do so.
great question, I think the best solution for this would be to create a Student object just like you thought!
public static class Student {
private final String name;
private final int id;
public Student(String name, int id) {
this.name = name;
this.id = id;
}
#Override
public String toString() {
return String.format("name=%s, id=%s", name, id);
}
}
public static class School {
private final List<Student> students;
public School(List<Student> students) {
this.students = students;
}
public void add(Student student) {
students.add(student);
}
public List<Student> getStudents() {
return students;
}
}
public static void main(String... args) {
School school = new School(new ArrayList<>());
school.add(new Student("jason", 1));
school.add(new Student("jonny", 2));
school.getStudents().forEach(System.out::println);
}
Non-OOP
Loop the pair of lists.
First sanity-check: Are the two lists the same size?
if( students.size() != ids.size() ) { … Houston, we have a problem }
Then loop. Use one index number to pull from both lists.
for( int index = 0 ;
index < students.size() ;
index ++
)
{
System.out.println(
students.get( index ) +
" | " +
ids.get( index )
) ;
}
OOP
The object-oriented approach would be to define a class. The class would have two member fields, the name and the id of the particular student.
Then create a method that outputs a String with your desired output.
All this has been covered many times on Stack Overflow. So search to learn more. For example: Creating simple Student class and How to override toString() properly in Java?
Uncomment and modify your toString() method as below. It will print both student and id.
#Override
public String toString() {
return student.toString() + id.toString();
}
If you want to have Student to Id mapping, best is to have them in Map collection. Id as key and student name as value.

Creating two constructors with objects that call to other java files

I don't really know if my question makes sense but my assignment says:
"Write a third class, StudentRecord, that has two attributes:
Student stu;
Address addr;
and two constructors. The first constructor is given a Student object and an Address object to initialize the attributes. The second constructor is given a first name, a last name, a student ID, a gpa, a street address, a city, a state, and a zipcode and uses these to initialize the attributes"
I don't understand how exactly I'm supposed to make two constructors take info from two different java files.
Here's the code I have for the third class named "StudentRecord".
I have no doubt it's incorrect.
public class StudentRecord {
Student stu;
Address addr;
public StudentRecord() {
Student stu;
Address addr;
}
public StudentRecord(String _fName, String _lName, int _id, double _gpa, String _street, String _city, String _state, int _zip){
}
public String toString() {
return String.format(stu + "\n" + addr);
}
}
Here's the code I have for the TestStudentRecord class, all I get is
"null null" when I run the program.
public class TestStudentRecord {
public static void main(String[] args) {
StudentRecord stu1 = new StudentRecord("Jane", "Brown", 182765, 2.333, "13 Flower St.", "Pulteneyville", "NY", 14386);
System.out.println(stu1);
}
}
All I get is "null null" when I run the program instead of the toString method giving me the student info I have typed into the test class.
For those asking for the Student and Address classes, here you go:
public class Student {
// attributes of a Student
private String firstName;
private String lastName;
private int studentId;
private double gpa;
/**
* Student constructor.
* #param _fName student's first name
* #param _lName student's last name
* #param _id student's id number
* #param _gpa students GPA
*/
public Student(String _fName, String _lName, int _id, double _gpa) {
firstName = _fName;
lastName = _lName;
studentId = _id;
gpa = _gpa;
}
/**
* getFirstName - Accessor for first name
* #return the student's first name
*/
public String getFirstName() {
return firstName;
}
/**
* getLastName - Accessor for last name
* #return the student's last name
*/
public String getLastName() {
return lastName;
}
/**
* getId - Accessor for ID
* #return the student's ID
*/
public int getStudentId() {
return studentId;
}
/**
* getGpa - Accessor for gpa
* #return the student's gpa
*/
public double getGpa() {
return gpa;
}
/**
* setFirstName - Mutator for first name
* #param the new first name
*/
public void setFirstName(String _fName) {
firstName = _fName;
}
/**
* setLastName - Mutator for last name
* #param the new last name
*/
public void setLastName(String _lastName) {
lastName = _lastName;
}
/**
* setStudentId - Mutator for ID
* #param the new ID
*/
public void setStudentId(int _id) {
studentId = _id;
}
/**
* setGpa - Mutator for gpa
* #param the new gpa
*/
public void setGpa(double _gpa) {
gpa = _gpa;
}
// toString Method
public String toString() {
return String.format(getLastName() + ", " + getFirstName() + "\n" + "ID: " + getStudentId() + " GPA: %3.1f", getGpa());
}
}
public class Address {
private String street;
private String city;
private String state;
private int zip;
public Address(String _street, String _city, String _state, int _zip) {
street = _street;
city = _city;
state = _state;
zip = _zip;
}
// Accessors
public String getStreet() {
return street;
}
public String getCity() {
return city;
}
public String getState() {
return state;
}
public int getZip() {
return zip;
}
// Mutators
public void setStreet(String _street) {
street = _street;
}
public void setCity(String _city) {
city = _city;
}
public void setState(String _state) {
state = _state;
}
public void setZip(int _zip) {
zip = _zip;
}
// toString Method
public String toString() {
return String.format(getStreet() + "\n" + getCity() + ", " + getState() + " " + getZip());
}
}
would suggest you to please follow below approach to initialize your object through argumented construtor.
public class StudentRecord {
Student stu;
Address addr;
public StudentRecord() {
Student stu;
Address addr;
}
public StudentRecord(String _fName, String _lName, int _id, double _gpa, String _street, String _city, String _state, int _zip){
this.stu = new Student(_fName, _lName, _id, _gpa);
this.addr=new Address(_street,_city,_state,_zip);
}
public String toString() {
return String.format(stu + "\n" + addr);
}
}
As you have already overided toString method in address and student class so you will get the object.
Your constructor is like below. Empty Constructor will not assign values to your class variables.
public StudentRecord(String _fName, String _lName, int _id, double _gpa, String _street, String _city, String _state, int _zip){
}
it should be like below as mentioned by Eran.
public StudentRecord(String _fName, String _lName, int _id, double _gpa, String _street, String _city, String _state, int _zip){
this.stu = new Student(_fName, _lName, _id, _gp);
this.addr = new Address(_street, _city, _state, _zip);
}
Now your toString will have the values for stu and addr. Which will get printed.
You have to initilize the variables with this.{variable name} = {variable name}.
Also it is often better to chain the Constructors (see How do I call one constructor from another in Java?), in this way changes in classes, with many constructors, are way easier to implement.
I would also suggsest to rename your variables, because in Java they should not start with an underscore (see https://www.javatpoint.com/java-naming-conventions).
public class StudentRecord {
Student student;
Address addr;
public StudentRecord(Student student, Address addr) {
this.student = student;
this.addr = addr;
}
public StudentRecord(String fName, String lName, int id, double gpa, String street, String city, String state, int zip){
this(new Student(fName, lName, id, gpa),
new Address(street,city,state,zip));
}
public String toString() {
return String.format(student + "\n" + addr);
}
}

Creating an array with 3 variables

I am trying to create an array of students which will contain 3 different types of students and each of the students will have 3 variables name, and 2 grades.
This is what I have done so far, and it gives me the following error cannot find symbol.
Main class:
public class JavaLab5 {
public static final int DEBUG = 0;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Student s[] = new Student[10];
s[0] = new MathStudent(Smith,14,15);
s[1] = new MathStudent(Jack,16,19);
s[2] = new MathStudent(Victor,18,21);
s[3] = new MathStudent(Mike,23,28);
s[4] = new ScienceStudent(Dave,32,25);
s[5] = new ScienceStudent(Oscar,28,56);
s[6] = new ScienceStudent(Peter,29,28);
s[7] = new ComputerStudent(Philip,25,38);
s[8] = new ComputerStudent(Shaun,34,39);
s[9] = new ComputerStudent(Scott,45,56);
for (int loop = 0; loop < 10; loop++) {
System.out.println(s[loop].getSubjects());
System.out.print(loop + " >>" + s[loop]);
}
}
}
This is the Student class:
public class Student {
private String name;
//private int age;
//public String gender = "na";
public static int instances = 0;
// Getters
//public int getAge() {
//return this.age;
//}
public String getName() {
return this.name;
}
// Setters
//public void setAge(int age) {
//this.age = age;
//}
public void setName(String name) {
if (JavaLab5.DEBUG > 3) System.out.println("In Student.setName. Name = "+ name);
this.name = name;
}
/**
* Default constructor. Populates name,age and gender
* with defaults
*/
public Student() {
instances++;
//this.age = 18;
this.name = "Not Set";
//this.gender = "Not Set";
}
/**
* Constructor with parameters
* #param age integer
* #param name String with the name
*/
public Student(String name) {
//this.age = age;
this.name = name;
}
/**
* Gender constructor
* #param gender
*/
//public Student(String gender) {
//this(); // Must be the first line!
//this.gender = gender;
//}
/**
* Destructor
* #throws Throwable
*/
protected void finalize() throws Throwable {
//do finalization here
instances--;
super.finalize(); //not necessary if extending Object.
}
public String toString () {
return "Name: " + this.name; //+ " Age: " + this.age + " Gender: "
//+ this.gender;
}
public String getSubjects() {
return this.getSubjects();
}
}
and this is the MathStudent class which inherits from the Student class:
public class MathStudent extends Student {
private float algebraGrade;
private float calculusGrade;
/**
* Default constructor
* #param name
* #param algebraGrade
* #param calculusGrade
*/
public MathStudent(String name, float algebraGrade, float calculusGrade) {
super();
this.algebraGrade = algebraGrade;
this.calculusGrade = calculusGrade;
}
public MathStudent() {
super();
algebraGrade = 6;
calculusGrade = 4;
}
// Getters
public void setAlgebraGrade(float algebraGrade){
this.algebraGrade = algebraGrade;
}
public void setCalculusGrade(float calculusGrade){
this.calculusGrade = calculusGrade;
}
// Setters
public float getAlgebraGrade() {
return this.algebraGrade;
}
public float getCalculusGrade() {
return this.calculusGrade;
}
/**
* Display information about the subject
* #return
*/
#Override
public String getSubjects(){
return(" Math Student >> " + "Algebra Grade: " + algebraGrade
+ " Calculus Grade: " + calculusGrade);
}
}
Check how you instantiate students, i.e.
new MathStudent(Smith,14,15);
The name should be in quotes like "Smith"
new MathStudent("Smith",14,15);
Otherwise Smith will be interpreted as variable and this one is not defined.

Creating a student arraylist to add students to course class Java

Im trying to create a student arraylist to a a course class so that when a student is added the arraylist is increases. this is the code I have so far:
import java.util.ArrayList;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author Saj
*/
public class Course {
private String courseName;
private int noOfStudents;
private String teacher;
public static int instances = 0;
//Getters
public String getCourseName(){
return this.courseName;
}
public int getNoOfStudents(){
return this.noOfStudents;
}
public String getTeacher(){
return this.teacher;
}
//Setters
public void setCourseName(String courseName){
this.courseName = courseName;
}
public void setNoOfStudents(int noOfStudents){
this.noOfStudents = noOfStudents;
}
public void setTeacher(String teacher){
this.teacher = teacher;
}
/**
* Default constructor. Populates course name, number of students with defaults
*/
public Course(){
instances++;
this.noOfStudents = 0;
this.courseName = "Not Set";
this.teacher = "Not Set";
}
/**
* Constructor with parameters
* #param noOfStudents integer
* #param courseName String with the Course name
* #param teacher String with the teacher
*/
public Course(int noOfStudents, String courseName, String teacher){
this.noOfStudents = noOfStudents;
this.courseName = courseName;
this.teacher = teacher;
}
}
Im unsure how to implement the array list. Can someone point me in the right direction.
With a little bit of research you can find many tutorials to achieve what you intend, but i'll try to set you in the right path just so you have an answear and somewhere to start.
What is a Student ?
Is it a String containing just a name, is it an object that represents a student that can have some properties ?
One example is
public class Student{
private int number;
private String name;
private int age;
// Basically anything that makes sense for a student.
public Student(int number, String name, int age){
this.number = number;
this.name = name;
this.age = age;
}
// .... Getters and Setters.
}
You need some place to store every Student added to the course, that is what the ArrayList is for i.e
List<Student> students = new ArrayList<Student>();
Student foo = new Student(23, "Foo", 22);
students.add(foo); // This is how you add to a List (in this case a List of Student objects and more precisely an ArrayList of Students).
You will need to keep the list in your course class as an instance variable, and add a method in wich you can pass a student and inside the method all you have to is add to your list of students, you may even do some validation if you want.
If you have more doubts first search for a solution before asking questions that can easily be found.
Here are some references:
Java List
Java ArrayList
EDIT the way you are adding your students is almost done but you have an error and also your list of students only resides inside the constructor, wich means you cannot use the list for saving students outside.
Below is the correct code
/**
* Constructor with parameters
* #param noOfStudents integer
* #param courseName String with the Course name
* #param teacher String with the teacher
*/
public Course(int noOfStudents, String courseName, String teacher){
this.studentList = new ArrayList<Student>(); // The declaration is in above in your class, as an instance variable.
this.courseName = courseName;
this.teacher = teacher;
}
ArrayList<Student> studentList; // You can move this so it sits above besides your other variables, but it will also work like this.
public boolean addStudent(Student student){
if (student==null || studentList.contains(student)) { // You had Student.contains, wich will give an error because Student (class) doesnt have a static method named contains.
return false;
}
studentList.add(student); // you had the same problem here, you had Student.add(student), wich is wrong and it would not compile.
return true;
}
Be sure that you have created the Student class and it is without any errors.
Tested and working code, change it to fullfill your needs more precisely
import java.util.ArrayList;
public class Course {
private String courseName;
private int noOfStudents;
private String teacher;
public static int instances = 0;
private ArrayList<Student> studentList;
//Getters
public String getCourseName(){
return this.courseName;
}
public int getNoOfStudents(){
return this.noOfStudents;
}
public String getTeacher(){
return this.teacher;
}
//Setters
public void setCourseName(String courseName){
this.courseName = courseName;
}
public void setNoOfStudents(int noOfStudents){
this.noOfStudents = noOfStudents;
}
public void setTeacher(String teacher){
this.teacher = teacher;
}
/**
* Default constructor. Populates course name, number of students with defaults
*/
public Course(){
instances++;
this.noOfStudents = 0;
this.courseName = "Not Set";
this.teacher = "Not Set";
}
/**
* Constructor with parameters
* #param noOfStudents integer
* #param courseName String with the Course name
* #param teacher String with the teacher
*/
public Course(int noOfStudents, String courseName, String teacher){
this.studentList = new ArrayList<Student>();
this.courseName = courseName;
this.teacher = teacher;
}
public boolean addStudent(Student student){
if (student==null || studentList.contains(student)) {
return false;
}
studentList.add(student);
return true;
}
public void printStudents(){
for(Student s : studentList)
System.out.println(s.getName() + ", with " + s.getAge() + " year(s)");
}
public static class Student{
private int number;
private String name;
private int age;
// Basically anything that makes sense for a student.
public Student(int number, String name, int age){
this.number = number;
this.name = name;
this.age = age;
}
// .... Getters and Setters.
public int getNumber(){
return this.number;
}
public String getName(){
return this.name;
}
public int getAge(){
return this.age;
}
}
// Testing code
public static void main(String[] args){
Course oop = new Course(6, "Object Oriented Programming", "LeBron James");
oop.addStudent(new Course.Student(6, "Michael Jordan", 56));
oop.addStudent(new Course.Student(23, "Kyrie Irving", 24));
oop.addStudent(new Course.Student(14, "Kevin Love", 27));
System.out.println(oop.getCourseName() + " has the following students");
oop.printStudents();
}
}
Just add attribute to your class
List<Student> students;
In constructors, initialize this list:
students = new ArrayList<>();
Create method to add student to list:
public boolean addStudent(Student stud) {
if (stud == null || students.contains(stud)) {
return false;
}
students.add(stud);
return true;
}
Also check https://docs.oracle.com/javase/8/docs/api/java/util/List.html for documentation of list.
Question is, do you want to add students in constructor? If so, add parameter to your constructor
public Course(int noOfStudents, String courseName,
String teacher, List<Student> students){
this.noOfStudents = noOfStudents;
this.courseName = courseName;
this.teacher = teacher;
this.students = new Arraylist<>(students);
}

i have trouble with printing an array after reading it in JAVA

i have problem with printing the array after reading it. After printing, the address of memory is printed, not value of the array. What can i do for that ?
public class MyClass
{
Student St = new Student();
Student[]Array1 = new Student[10];
void AddList()
{
Scanner Scan = new Scanner(System.in);
for (int i=0; i<Array1.length & i<ArrayF1.length; i++)
{
System.out.println("Enter Student NAME Number " + (i+1) + ":");
Array1[i] = new Student();
Array1[i].setName(Scan.next());
//System.out.println("Enter Student MARK Number " + (i+1) + ":");
//St.setMark(Scan.nextFloat());
}
}
this is my print method. The result of print is like this
(studentproject.Student#1a758cb)
void PrintList()
{
for (int i=0; i<Array1.length; i++)
{
System.out.println(Array1[i]);
}
}
this is my Student Class that i have all my setter and getter method on that ... So i have 3 Class how can i work with this 3 class and in one of them get the data and in another print the Mark data and in third class print the Student Name data ... how can i do that ... i do some code but i dont know is it correct or not ... thanks for your help ...
public class Student
{
private String Name;
private float Mark;
/**
* #return the Name
*/
public String getName() {
return Name;
}
/**
* #param Name the Name to set
*/
public void setName(String Name) {
this.Name = Name;
}
/**
* #return the Mark
*/
public float getMark() {
return Mark;
}
/**
* #param Mark the Mark to set
*/
public void setMark(float Mark) {
this.Mark = Mark;
}
}
Just override the toString() method in Student class, and return the appropriate string you want to get printed when you print an instance.
It may look like: -
#Override
public String toString() {
return "Name: " + studentName;
}
Currently, the default implementation of toString() method of Object class is invoked, and what you are seeing is the format returned from that method, which is of the form - Type#hashCode
Here I've added some stuff how toString() method can be override
public class Student {
private String name;
private int id;
float mark;
public Student() {
}
public Student(String name, int id) {
this.name = name;
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getMark() {
return mark;
}
public void setMark(float mark) {
this.mark = mark;
}
#Override
public String toString() {
return "Student[ID:" + id + ",Name:" + name + ",Mark:"+mark+"]";
}
public void printStudentInfo() {
// print all the details of student
}
public static void main(String[] args) {
Student[] students = new Student[10];
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < students.length; i++) {
System.out.println("Enter Student Name " + (i + 1) + ":");
String name = scanner.nextLine();
Student student = new Student(name, i + 1);
System.out.println("Enter Student MARK Number " + (i + 1) + ":");
float mark = scanner.nextFloat();
student.setMark(mark);
students[i]=student;
}
for(Student student:students) {
// by default toStirng method is called
System.out.println(student);
//or you can call like
//student.printStudentInfo();
}
}
}

Categories